package com.jeeplus.modules.api;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse;

import com.jeeplus.common.utils.time.DateUtil;
import com.jeeplus.modules.activity.entity.Activity;
import com.jeeplus.modules.activity.service.ActivityService;
import com.jeeplus.modules.api.utils.*;
import com.jeeplus.modules.cfm.entity.Cfm;
import com.jeeplus.modules.cfm.mapper.CfmMapper;
import com.jeeplus.modules.cfm.service.CfmService;
import com.jeeplus.modules.collectstore.entity.CollectStore;
import com.jeeplus.modules.gift.entity.Gift;
import com.jeeplus.modules.gift.mapper.GiftMapper;
import com.jeeplus.modules.gift.service.GiftService;

import com.jeeplus.modules.hkqy.entity.Hkqy;
import com.jeeplus.modules.hkqy.mapper.HkqyMapper;
import com.jeeplus.modules.hkqy.service.HkqyService;
import com.jeeplus.modules.ktq.entity.Ktq;
import com.jeeplus.modules.ktq.service.KtqService;
import com.jeeplus.modules.prize.entity.Prize;
import com.jeeplus.modules.prize.mapper.PrizeMapper;
import com.jeeplus.modules.prize.service.PrizeService;
import com.jeeplus.modules.vip.entity.Vip;
import com.jeeplus.modules.vip.mapper.VipMapper;
import com.jeeplus.modules.vip.service.VipService;
import com.jeeplus.modules.xfq.entity.Xfq;
import com.jeeplus.modules.xfq.mapper.XfqMapper;
import com.jeeplus.modules.xfq.service.XfqService;
import com.jeeplus.modules.kyd.entity.Kyd;
import com.jeeplus.modules.kyd.mapper.KydMapper;
import com.jeeplus.modules.kyd.service.KydService;
import com.jeeplus.modules.llbt.entity.Llbt;
import com.jeeplus.modules.llbt.mapper.LlbtMapper;
import com.jeeplus.modules.productorder.entity.OrderItem;
import com.jeeplus.modules.ptc.entity.Ptc;
import com.jeeplus.modules.ptc.mapper.PtcMapper;
import com.jeeplus.modules.ptc.service.PtcService;
import com.jeeplus.modules.stocom.mapper.StocomMapper;
import com.jeeplus.modules.stocom.service.StocomService;
import com.jeeplus.modules.xhq.entity.Xhq;
import com.jeeplus.modules.xhq.mapper.XhqMapper;
import com.jeeplus.modules.shopbusorder.entity.ShopbusOrder;
import com.jeeplus.modules.shopbusorder.service.ShopbusOrderService;
import com.jeeplus.modules.taokeorder.service.TTaokeOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.sms.FeigeSMSUtil;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.MD5Util;
import com.jeeplus.common.utils.net.IPUtil;
import com.jeeplus.common.utils.number.RandomUtil;
import com.jeeplus.common.utils.time.DateFormatUtil;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.access.entity.Access;
import com.jeeplus.modules.access.service.AccessService;
import com.jeeplus.modules.address.entity.Address;
import com.jeeplus.modules.address.service.AddressService;
import com.jeeplus.modules.api.req.ReqJson;
import com.jeeplus.modules.api.res.ResJson;
import com.jeeplus.modules.api.service.ApiService;
import com.jeeplus.modules.api.utils.AlipayUtils;
import com.jeeplus.modules.api.utils.CreditCardUtils;
import com.jeeplus.modules.api.utils.DingdanxiaUtils;
import com.jeeplus.modules.api.utils.MiaoyouquanUtils;
import com.jeeplus.modules.api.utils.PhoneUtils;
import com.jeeplus.modules.api.utils.WohuiEntity;
import com.jeeplus.modules.api.utils.WohuiUtils;
import com.jeeplus.modules.api.utils.WxPayUtils;
import com.jeeplus.modules.api.utils.ZhongTaiUtil;
import com.jeeplus.modules.banner.entity.Banner;
import com.jeeplus.modules.banner.service.BannerService;
import com.jeeplus.modules.button.entity.Button;
import com.jeeplus.modules.button.service.ButtonService;
import com.jeeplus.modules.cart.entity.Cart;
import com.jeeplus.modules.cart.service.CartService;
import com.jeeplus.modules.collectstore.service.CollectStoreService;
import com.jeeplus.modules.college.entity.College;
import com.jeeplus.modules.college.service.CollegeService;
import com.jeeplus.modules.comment.entity.Comment;
import com.jeeplus.modules.comment.service.CommentService;
import com.jeeplus.modules.couponorder.entity.CouponOrder;
import com.jeeplus.modules.couponorder.service.CouponOrderService;
import com.jeeplus.modules.creditcard.entity.CreditCard;
import com.jeeplus.modules.creditcard.service.CreditCardService;
import com.jeeplus.modules.creditcardorder.entity.CreditCardOrder;
import com.jeeplus.modules.creditcardorder.service.CreditCardOrderService;
import com.jeeplus.modules.customer.entity.Customer;
import com.jeeplus.modules.customer.service.CustomerService;
import com.jeeplus.modules.delivery.entity.Delivery;
import com.jeeplus.modules.delivery.service.DeliveryService;
import com.jeeplus.modules.grouporder.entity.GroupOrder;
import com.jeeplus.modules.grouporder.entity.OrderGift;
import com.jeeplus.modules.grouporder.service.GroupOrderService;
import com.jeeplus.modules.llbt.service.LlbtService;
import com.jeeplus.modules.xhq.service.XhqService;
import com.jeeplus.modules.grouprefund.entity.GroupRefund;
import com.jeeplus.modules.grouprefund.service.GroupRefundService;
import com.jeeplus.modules.keyword.entity.Keyword;
import com.jeeplus.modules.keyword.service.KeywordService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.msg.entity.Msg;
import com.jeeplus.modules.msg.service.MsgService;
import com.jeeplus.modules.msgexample.entity.MsgExample;
import com.jeeplus.modules.msgexample.service.MsgExampleService;
import com.jeeplus.modules.notice.entity.Notice;
import com.jeeplus.modules.notice.service.NoticeService;
import com.jeeplus.modules.pickday.entity.PickDay;
import com.jeeplus.modules.pickday.service.PickDayService;
import com.jeeplus.modules.product.entity.Product;
import com.jeeplus.modules.product.entity.ProductSkuname;
import com.jeeplus.modules.product.mapper.ProductSkunameMapper;
import com.jeeplus.modules.product.service.ProductService;
import com.jeeplus.modules.productcategory.entity.ProductCategory;
import com.jeeplus.modules.productcategory.service.ProductCategoryService;
import com.jeeplus.modules.productgift.entity.ProductGift;
import com.jeeplus.modules.productgift.service.ProductGiftService;
import com.jeeplus.modules.productgroup.entity.ProductGroup;
import com.jeeplus.modules.productgroup.service.ProductGroupService;
import com.jeeplus.modules.productorder.entity.ProductOrder;
import com.jeeplus.modules.productorder.service.ProductOrderService;
import com.jeeplus.modules.productsku.entity.ProductSku;
import com.jeeplus.modules.productsku.service.ProductSkuService;
import com.jeeplus.modules.proxylog.service.ProxyLogService;
import com.jeeplus.modules.proxyorder.entity.ProxyOrder;
import com.jeeplus.modules.proxyorder.service.ProxyOrderService;
import com.jeeplus.modules.proxyprice.entity.ProxyPrice;
import com.jeeplus.modules.proxyprice.service.ProxyPriceService;
import com.jeeplus.modules.proxyproduct.entity.ProxyProduct;
import com.jeeplus.modules.proxyproduct.service.ProxyProductService;
import com.jeeplus.modules.recharge.entity.Recharge;
import com.jeeplus.modules.recharge.service.RechargeService;
import com.jeeplus.modules.rechargeorder.entity.RechargeOrder;
import com.jeeplus.modules.rechargeorder.service.RechargeOrderService;
import com.jeeplus.modules.sharepicture.entity.SharePicture;
import com.jeeplus.modules.sharepicture.service.SharePictureService;
import com.jeeplus.modules.shop.entity.Shop;
import com.jeeplus.modules.shop.service.ShopService;
import com.jeeplus.modules.shopcoupon.entity.ShopCoupon;
import com.jeeplus.modules.shopcoupon.service.ShopCouponService;
import com.jeeplus.modules.store.entity.Store;
import com.jeeplus.modules.store.mapper.StoreMapper;
import com.jeeplus.modules.store.service.StoreService;
import com.jeeplus.modules.sys.entity.Area;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.mapper.UserMapper;
import com.jeeplus.modules.sys.service.AreaService;
import com.jeeplus.modules.sys.utils.UserUtils;

import net.oschina.j2cache.CacheProviderHolder;
import sun.rmi.rmic.iiop.NCInterfaceType;


/**
 * APP接口
 * @author Administrator
 *
 */
@CrossOrigin(origins = "*")
@Controller
@RequestMapping(value = "/api")
public class ApiController extends BaseController {
	@Autowired
	private ApiService apiService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private CollegeService collegeService;
	@Autowired
	private BannerService bannerService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private ButtonService buttonService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private AccessService accessService;
	@Autowired
	private ShopCouponService shopCouponService;
	@Autowired
	private RechargeService rechargeService;
	@Autowired
	private RechargeOrderService rechargeOrderService;
	@Autowired
	private CollectStoreService collectStoreService;
	@Autowired
	private ProductService productService;
	@Autowired
	private ProductSkuService productSkuService;
	@Autowired
	private CartService cartService;
	@Autowired
	private KeywordService keywordService;
	@Autowired
	private ShopService shopService;
	@Autowired
	private CommentService commentService;
	@Autowired
	private MsgService msgService;
	@Autowired
	private CouponOrderService couponOrderService;
	@Autowired
	private ShopbusOrderService shopbusorderService;
	@Autowired
	private ProductOrderService productOrderService;
	@Autowired
	private AddressService addressService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private SharePictureService sharePictureService;
	@Autowired
	private ProductGroupService productGroupService;
	@Autowired
	private GroupOrderService groupOrderService;
	@Autowired
	private LlbtService llbtService;
	@Autowired
	private XhqService xhqService;
	@Autowired
	private PtcService ptcService;
	@Autowired
	private PtcMapper ptcMapper;
	@Autowired
	private HkqyService hkqyService;
	@Autowired
	private HkqyMapper hkqyMapper;
	@Autowired
	private KydService kydService;
	@Autowired
	private KydMapper kydMapper;
	@Autowired
	private GiftService giftService;
	@Autowired
	private GiftMapper giftMapper;
	@Autowired
	private KtqService ktqService;
	@Autowired
	private PrizeMapper prizeMapper;
	@Autowired
	private PrizeService prizeService;
	@Autowired
	private XfqMapper xfqMapper;
	@Autowired
	private XfqService xfqService;
	@Autowired
	private VipMapper vipMapper;
	@Autowired
	private VipService vipService;
	@Autowired
	private CfmMapper cfmMapper;
	@Autowired
	private CfmService cfmService;
	@Autowired
	private XhqMapper xhqMapper;
	@Autowired
	private LlbtMapper llbtMapper;
	@Autowired
	private AreaService areaService;
	@Autowired
	private ProxyLogService proxyLogService;
	@Autowired
	private ProxyPriceService proxyPriceService;
	@Autowired
	private ProductGiftService productGiftService;
	@Autowired
	private GroupRefundService groupRefundService;
	@Autowired
	private CreditCardService creditCardService;
	@Autowired
	private CreditCardOrderService creditCardOrderService;
	@Autowired
	private ProxyOrderService proxyOrderService;
	@Autowired
	private ProxyProductService proxyProductService;
	@Autowired
	private DeliveryService deliveryService;
	@Autowired
	private MsgExampleService msgExampleService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private ProductSkunameMapper productSkunameMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private StoreMapper storeMapper;
	@Autowired
	private ProductCategoryService productCategoryService;
	@Autowired
	private PickDayService pickDayService;
	@Autowired
	private TTaokeOrderService tTaokeOrderService;

	private String wohuiId = "35278AE6B4E14F1F9582937C5C836453";

	//Logger apiLogger = Logger.getLogger(ApiController.class);

	@PostMapping("/test")
	@ResponseBody
	public ResJson test(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	@PostMapping("/importSysUser")
	@ResponseBody
	public ResJson importSysUser(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("导入失败");
		int success = 0;
		int fail = 0;
		StringBuilder msgs = new StringBuilder();
		try {
			File jsonFile = new File("D:/Documents/Desktop/SQL/sysuser.json");
			Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			reader.close();
			JSONObject jsonObject = JSONObject.parseObject(sb.toString());
			if (jsonObject != null) {
				JSONArray jsonArray = jsonObject.getJSONArray("RECORDS");
				if (jsonArray != null && !jsonArray.isEmpty()) {
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject o = jsonArray.getJSONObject(i);
						if (StringUtils.isNotBlank(o.getString("wohui_guid"))) {
							User user = new User();
							user.setId(o.getString("wohui_guid"));
							user.setLoginName(o.getString("username"));
							user.setPassword(MD5Util.md5("wohui365"));
							user.setName(o.getString("merchname"));
							user.setMobile(o.getString("wohui_user"));
							user.setLoginFlag("1");
							user.setCreateBy(new User("1"));
							user.setCreateDate(new Date());
							user.setUpdateBy(new User("1"));
							user.setUpdateDate(new Date());
							List<Role> roleList = Lists.newArrayList();
							roleList.add(new Role("1"));
							user.setRoleList(roleList);

							try {
								userMapper.insert(user);
								userMapper.insertUserRole(user);
								success++;
							} catch (Exception e) {
								fail++;
								msgs.append(o.getString("username")).append(",");
							}
						} else {
							fail++;
							msgs.append(o.getString("username")).append(",");
						}


					}
				}
			}

			res.setResult("0");
			res.setResultNote("导入完成，成功" + success + "个，失败" + fail + "个。\t\n失败username：" + msgs.toString());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	@PostMapping("/initProductSku")
	@ResponseBody
	public ResJson initProductSku(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("初始化失败");
		try {
			List<Map<String, Object>> pidList = productSkuService.executeSelectSql("SELECT * FROM (SELECT a.id,COUNT(b.id) count FROM t_product a LEFT JOIN t_product_sku b ON a.id = b.product_id GROUP BY a.id) s WHERE s.count = 0");
			if (pidList != null && !pidList.isEmpty()) {
				for (Map<String, Object> map : pidList) {
					String pid = map.get("id").toString();
					ProductSkuname productSkuname = new ProductSkuname();
					productSkuname.setProduct(new Product(pid));
					productSkuname.setTitle("默认");
					productSkuname.setId(IdGen.uuid());
					productSkuname.setCreateDate(new Date());
					productSkuname.setUpdateDate(new Date());
					productSkunameMapper.insert(productSkuname);

					ProductSku productSku = new ProductSku();
					productSku.setProduct(new Product(pid));
					productSku.setStock(0);
					productSku.setOldPrice("0");
					productSku.setDiscount("0");
					productSku.setPrice("0");
					productSku.setGroupPrice("0");
					productSku.setAmount("0");
					JSONArray content = new JSONArray();
					JSONObject sku = new JSONObject();
					sku.put("id", productSkuname.getId());
					sku.put("value", "默认");
					content.add(sku);
					productSku.setContent(content.toJSONString());
					productSkuService.save(productSku);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	@PostMapping("/importStore")
	@ResponseBody
	public ResJson importStore() {
		ResJson res = new ResJson();
		res.setResultNote("导入失败");
		int success = 0;
		int fail = 0;
		StringBuilder msgs = new StringBuilder();
		try {
			File jsonFile = new File("D:/Documents/Desktop/SQL/store_new.json");
			Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			reader.close();
			JSONObject jsonObject = JSONObject.parseObject(sb.toString());
			if (jsonObject != null) {
				JSONArray jsonArray = jsonObject.getJSONArray("RECORDS");
				if (jsonArray != null && !jsonArray.isEmpty()) {
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject o = jsonArray.getJSONObject(i);
						if ("1".equals(o.getString("status"))) {
							Store store = new Store();
							store.setIsNewRecord(true);
							store.setId(o.getString("id"));
							store.setMember(new Member(o.getString("my_guid")));
							store.setStoreCode(o.getString("UnionCode"));
							store.setProductCode(o.getString("gbianma"));
							store.setTitle(o.getString("merchname"));
							store.setCategory(o.getString("salecate"));
							store.setCity(o.getString("address"));
							store.setUsername(o.getString("realname"));
							store.setPhone(o.getString("mobile"));
							store.setInvite(new Member(o.getString("guid")));
							store.setCreateDate(new Date(o.getLongValue("jointime")));
							store.setState("0");
							store.setAuditState("2");
							store.setAmount(StringUtils.isNotBlank(o.getString("zf_money")) ? o.getString("zf_money") : "0");
							store.setAuditDate(new Date(o.getLongValue("applytime")));
							store.setRemarks(o.getString("remark"));
							store.setBalance("0");
							store.setHuitian("1");
							store.setFreight("0");
							store.setShangqiao(o.getString("kefuurl"));
							store.setInvitePhone(o.getString("tuijian_phone"));
							store.setContent(o.getString("desc"));
							try {
								User user = userMapper.getByLoginName(new User(null, store.getPhone()));
								if (user == null) {
									user = new User();
									user.setId(IdGen.uuid());
									user.setLoginName(store.getPhone());
									user.setPassword(MD5Util.md5("wohui365"));
									user.setName(store.getTitle());
									user.setLoginFlag("1");
									user.setCreateBy(new User("1"));
									user.setCreateDate(new Date());
									user.setUpdateBy(new User("1"));
									user.setUpdateDate(new Date());
									List<Role> roleList = Lists.newArrayList();
									roleList.add(new Role("1"));
									user.setRoleList(roleList);
									userMapper.insert(user);
									userMapper.insertUserRole(user);
								}

								store.setUser(user);
								storeMapper.insert(store);
								success++;
							} catch (Exception e) {
								fail++;
								msgs.append(o.getString("id")).append(",");
								e.printStackTrace();
								logger.error(e.getMessage());
							}
						}
					}
				}
			}

			res.setResult("0");
			res.setResultNote("导入完成，成功" + success + "个，失败" + fail + "个。\t\n失败ID：" + msgs.toString());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	@PostMapping("/importSku")
	@ResponseBody
	public ResJson importSku() {
		ResJson res = new ResJson();
		res.setResultNote("导入失败");
		int success = 0;
		int fail = 0;
		StringBuilder msgs = new StringBuilder();
		JSONArray noList = new JSONArray();
		try {
			File jsonFile = new File("D:/Documents/Desktop/SQL/sku_value.json");
			Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			reader.close();
			JSONObject jsonObject = JSONObject.parseObject(sb.toString());
			if (jsonObject != null) {
				JSONArray jsonArray = jsonObject.getJSONArray("RECORDS");
				if (jsonArray != null && !jsonArray.isEmpty()) {
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject o = jsonArray.getJSONObject(i);
						String specId = o.getString("specs");
						int specCount = StringUtils.countMatches(specId, "_");
						if (specCount > 0) {
							String goods_item = o.getString("goods_item");
							int itemCount = StringUtils.countMatches(goods_item, "+");
							if (itemCount != specCount) {
								noList.add(o);
								continue;
							}
						}
						ProductSku productSku = new ProductSku();
						productSku.setIsNewRecord(true);
						productSku.setId(o.getString("optionid"));
						productSku.setProduct(new Product(o.getString("goodsid")));
						productSku.setStock(o.getIntValue("stock"));
						productSku.setOldPrice(o.getDouble("marketprice") + "");
						productSku.setPrice(o.getDouble("marketprice") + "");
						productSku.setDiscount("0");
						productSku.setGroupPrice(o.getDouble("marketprice") + "");
						productSku.setAmount("0");
						JSONArray content = new JSONArray();
						if (specCount == 0) {
							JSONObject sku = new JSONObject(true);

							Object objId = productSkuService.executeGetSql("select specid from temp_spec_item where id='" + specId + "'");
							//sku.put("id", specId);
							sku.put("id", objId != null ? objId.toString() : "");
							sku.put("value", o.getString("goods_item"));
							content.add(sku);
						} else {
							String[] ids = specId.split("_");
							String[] item = o.getString("goods_item").split("\\+");
							for (int j = 0; j < ids.length; j++) {
								JSONObject sku = new JSONObject(true);
								Object objId = productSkuService.executeGetSql("select specid from temp_spec_item where id='" + ids[j] + "'");
								sku.put("id", objId != null ? objId.toString() : "");
								//sku.put("id", ids[j]);
								sku.put("value", item.length > j ? item[j] : "");
								content.add(sku);
							}
						}

						productSku.setContent(content.toString());
						try {
							productSkuService.save(productSku);
							success++;
						} catch (Exception e) {
							fail++;
							msgs.append(o.getString("id")).append(",");
						}
					}

				}
			}

			res.setResult("0");
			res.setResultNote("导入完成，成功" + success + "个，失败" + fail + "个。\t\n失败ID：" + msgs.toString());
			res.put("noList", noList);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/*
	@PostMapping("/importProductSku")
	@ResponseBody
	public ResJson importProductSku() {
		ResJson res = new ResJson();
		res.setResultNote("导入失败");
		int success = 0;
		int fail = 0;
		StringBuilder msgs = new StringBuilder();
		try {
			File jsonFile = new File("D:/Documents/Desktop/SQL/ims_ewei_shop_goods_spec_item.json");
			Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			reader.close();
			JSONObject jsonObject = JSONObject.parseObject(sb.toString());
			if (jsonObject != null) {
				JSONArray jsonArray = jsonObject.getJSONArray("RECORDS");
				if (jsonArray != null && !jsonArray.isEmpty()) {
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject o = jsonArray.getJSONObject(i);
						ProductSku productSku = new ProductSku();

						productSku.setIsNewRecord(true);
						productSku.setId(o.getString("id"));
						productSku.setProduct(new Product(o.getString("specid")));
						JSONArray content = new JSONArray();
						JSONObject obj = new JSONObject();
						obj.put("id", o.getString("specid"));
						obj.put("value", o.getString("title"));
						content.add(obj);
						productSku.setContent(content.toJSONString());
						productSku.setImage(o.getString("thumb"));
						try {
							productSkuService.save(productSku);
							success++;
						} catch (Exception e) {
							fail++;
							msgs.append(o.getString("id")).append(",");
						}

					}
				}
			}

			res.setResult("0");
			res.setResultNote("导入完成，成功" + success + "个，失败" + fail + "个。\t\n失败ID：" + msgs.toString());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	*/

	@PostMapping("/importProductSkuName")
	@ResponseBody
	public ResJson importProductSkuName() {
		ResJson res = new ResJson();
		res.setResultNote("导入失败");
		int success = 0;
		int fail = 0;
		StringBuilder msgs = new StringBuilder();
		try {
			File jsonFile = new File("D:/Documents/Desktop/SQL/ims_ewei_shop_goods_spec.json");
			Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			reader.close();
			JSONObject jsonObject = JSONObject.parseObject(sb.toString());
			if (jsonObject != null) {
				JSONArray jsonArray = jsonObject.getJSONArray("RECORDS");
				if (jsonArray != null && !jsonArray.isEmpty()) {
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject o = jsonArray.getJSONObject(i);
						ProductSkuname productSkuname = new ProductSkuname();
						productSkuname.setIsNewRecord(true);
						productSkuname.setId(o.getString("id"));
						productSkuname.setProduct(new Product(o.getString("goodsid")));
						productSkuname.setTitle(o.getString("title"));
						productSkuname.setCreateDate(new Date());
						productSkuname.setUpdateDate(new Date());
						try {

							productSkunameMapper.insert(productSkuname);
							success++;
						} catch (Exception e) {
							fail++;
							msgs.append(o.getString("id")).append(",");
						}

					}
				}
			}

			res.setResult("0");
			res.setResultNote("导入完成，成功" + success + "个，失败" + fail + "个。\t\n失败ID：" + msgs.toString());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	@PostMapping("/importProductCategory")
	@ResponseBody
	public ResJson importProductCategory() {
		ResJson res = new ResJson();
		res.setResultNote("导入失败");
		int success = 0;
		int fail = 0;
		StringBuilder msgs = new StringBuilder();
		try {
			File jsonFile = new File("D:/Documents/Desktop/SQL/ims_ewei_shop_category.json");
			Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			reader.close();
			JSONObject jsonObject = JSONObject.parseObject(sb.toString());
			if (jsonObject != null) {
				JSONArray jsonArray = jsonObject.getJSONArray("RECORDS");
				if (jsonArray != null && !jsonArray.isEmpty()) {
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject o = jsonArray.getJSONObject(i);
						ProductCategory productCategory = new ProductCategory();
						productCategory.setIsNewRecord(true);
						productCategory.setId(o.getString("id"));
						productCategory.setName(o.getString("name"));
						productCategory.setType(o.getString("level"));
						productCategory.setParent(new ProductCategory(o.getString("parentid")));
						productCategory.setSort(o.getIntValue("displayorder"));
						productCategory.setState("1".equals(o.getString("enabled")) ? "0" : "1");
						productCategory.setIcon(o.getString("thumb"));
						productCategory.setHot(o.getString("isrecommand"));

						try {

							productCategoryService.save(productCategory);
							success++;
						} catch (Exception e) {
							fail++;
							msgs.append(o.getString("id")).append(",");
						}

					}
				}
			}

			res.setResult("0");
			res.setResultNote("导入完成，成功" + success + "个，失败" + fail + "个。\t\n失败ID：" + msgs.toString());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	@PostMapping("/importProduct")
	@ResponseBody
	public ResJson importProduct() {
		ResJson res = new ResJson();
		res.setResultNote("导入失败");
		int success = 0;
		int fail = 0;
		StringBuilder msgs = new StringBuilder();
		try {
			File jsonFile = new File("D:/Documents/Desktop/SQL/product.json");
			//FileReader fileReader = new FileReader(jsonFile);
			Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			//fileReader.close();
			reader.close();
			JSONObject jsonObject = JSONObject.parseObject(sb.toString());
			if (jsonObject != null) {
				JSONArray jsonArray = jsonObject.getJSONArray("RECORDS");
				if (jsonArray != null && !jsonArray.isEmpty()) {
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject o = jsonArray.getJSONObject(i);
						if ("1".equals(o.getString("status"))) {
							Product product = new Product();
							product.setIsNewRecord(true);
							product.setId(o.getString("id"));
							product.setStore(new Store(o.getString("merchid")));
							product.setTitle(o.getString("title"));
							product.setSubtitle(o.getString("shorttitle"));
							product.setIcon(o.getString("thumb"));
							String images = o.getString("thumb_url");
							List<String> imgs = Lists.newArrayList();
							if (StringUtils.isNotBlank(images)) {
								String[] split = images.split(";");
								for (String s : split) {
									String replace = s.replace("\"", "");
									String[] split2 = replace.split(":");
									for (String img : split2) {
										if (img.startsWith("images")) {
											imgs.add(img);
										}
									}
								}
							}
							if (!imgs.isEmpty()) {
								product.setImages(StringUtils.join(imgs, "|"));
							}
							if (!"0".equals(o.getString("tcate"))) {
								product.setCategory(new ProductCategory(o.getString("tcate")));
							} else if (!"0".equals(o.getString("ccate"))) {
								product.setCategory(new ProductCategory(o.getString("ccate")));
							} else if (!"0".equals(o.getString("pcate"))) {
								product.setCategory(new ProductCategory(o.getString("pcate")));
							}
/*							if (StringUtils.isNotBlank(o.getString("tcate"))) {
								product.setCategory(new ProductCategory(o.getString("tcate")));
							} else if (StringUtils.isNotBlank(o.getString("ccate"))) {
								product.setCategory(new ProductCategory(o.getString("ccate")));
							} else if (StringUtils.isNotBlank(o.getString("pcate"))) {
								product.setCategory(new ProductCategory(o.getString("pcate")));
							}
*/
							product.setSales(o.getInteger("salesreal"));
							product.setHits(RandomUtil.nextInt(1000, 5000));
							product.setPoint(o.getString("yun_gold"));
							product.setContent(o.getString("content"));
							product.setOldPrice(o.getString("marketprice"));
							product.setDiscount(o.getString("yun_ingot"));

							product.setPrice(o.getBigDecimal("marketprice").subtract(o.getBigDecimal("yun_ingot")).toString());
							product.setGroupPrice(product.getPrice());
							product.setAmount(o.getString("settlementprice"));
							product.setIsHot(o.getString("ishot"));
							product.setIsNew(o.getString("isnew"));
							product.setState("0");
							product.setAuditState("1");
							product.setCreateDate(new Date());
							product.setAuditDate(new Date());
							product.setIsGroup("0");
							product.setIsFupin("0");

							try {
								productService.save(product);
								success++;
							} catch (Exception e) {
								fail++;
								msgs.append(o.getString("id")).append(",");
							}
						}

					}
				}
			}

			res.setResult("0");
			res.setResultNote("导入完成，成功" + success + "个，失败" + fail + "个。\t\n失败ID：" + msgs.toString());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 客服中心
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/customerList")
	@ResponseBody
	public ResJson customerList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			List<Customer> list = Lists.newArrayList();
			if (StringUtils.isNotBlank(req.getString("keyword"))) {
				Customer cus = new Customer();
				cus.setTitle(req.getString("keyword"));
				list = customerService.findList(cus);
			}
			if (list == null || list.isEmpty()) {
				Customer cus = new Customer();
				cus.setType("1");
				list = customerService.findList(cus);
			}
			for (Customer customer : list) {
				Map<String, String> map = Maps.newHashMap();
				map.put("title", customer.getTitle());
				map.put("content", customer.getContent());
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 商圈优惠券列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/findShopCouponList")
	@ResponseBody
	public ResJson findShopCouponList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			ShopCoupon shopCoupon = new ShopCoupon();
			shopCoupon.setState("1");
			shopCoupon.setAudit("1");
			String dataScope = " AND a.end_date > NOW() AND shop.state = '0' AND shop.audit_state = '2' ";
			shopCoupon.setDataScope(dataScope);
			Page<ShopCoupon> page = new Page<ShopCoupon>(req.getPageNo(), req.getPageSize());

			Page<ShopCoupon> pageInfo = shopCouponService.findPage(page, shopCoupon);
			res.setTotalPage(pageInfo.getTotalPage());
			for (ShopCoupon coupon : pageInfo.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("shopId", coupon.getShop().getId());
				map.put("shopName", coupon.getShop().getTitle());
				map.put("shopCode", coupon.getShop().getShopCode());
				map.put("shopLogo", getRealImage(coupon.getShop().getIcon()));
				map.put("shopAddr", coupon.getShop().getAddress());
				map.put("lon", coupon.getShop().getLon());
				map.put("lat", coupon.getShop().getLat());
				map.put("voucherId", coupon.getId());
				map.put("reachMoney", coupon.getMoney());
				map.put("price", coupon.getPrice());
				map.put("integral", coupon.getPoint());
				map.put("startTime", DateFormatUtil.ISO_ON_DATE_FORMAT.format(coupon.getStartDate()));
				map.put("endTime", DateFormatUtil.ISO_ON_DATE_FORMAT.format(coupon.getEndDate()));
				map.put("content", coupon.getContent());
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 根据GUID获取用户单品代理/批发云店铺 的及增选价格
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/getSinglePrice")
	@ResponseBody
	public ResJson getSinglePrice(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			String fee = "6.00";
			String price = "600.00";
			String cfmMargin = "500.00";
			String monthprice = "60.00";
			List<ProxyPrice> list = proxyPriceService.findList(new ProxyPrice());
			if (!list.isEmpty()) {
				fee = list.get(0).getPickPrice();
				price = list.get(0).getPrice();
				monthprice = list.get(0).getMonthprice();
				cfmMargin = list.get(0).getCfmMargin();
			}
			if (isBlank(req.getUid())){
				res.setResultNote("请先登录");
				return res;
			}
			// 调用三方会员系统
			List<WohuiEntity> list2 = Lists.newArrayList();
			list2.add(new WohuiEntity("UGUID", req.getUid()));
			JSONObject object = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, list2);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
				return res;
			}
			JSONArray data = object.getJSONArray("data");
			JSONObject obj = data.getJSONObject(0);
			String isDisCanXH = "1";// 是否可以选货  可以1  默认不可以0
			//年费判断
			//单品代理增选/批发云店铺 GoodsFreeCanNum>GoodsFreeHasNum
			if(obj.getIntValue("C_GoodsFreeCanNum") > obj.getIntValue("C_GoodsFreeHasNum") || obj.getIntValue("C_GoodsGiveNum") > 0 || obj.getIntValue("C_GoodsMSMFreeNum") > 0 || obj.getIntValue("C_PCANumTCGive") > 0 || obj.getIntValue("C_PCANumXFQGive") > 0){
				fee = "0.00";
			}
			res.put("isDisCanXH", isDisCanXH);
			res.put("fee", fee);
			res.put("price", price);
			res.put("cfmMargin", cfmMargin);
			res.put("monthprice", monthprice);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 增选单品代理产品
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/addProxyProduct")
	@ResponseBody
	public ResJson addProxyProduct(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("提交失败");
		try {
			if (isBlank(req.getUid(), req.getString("province"), req.getString("city"), req.getString("area"), req.getString("source"), req.getString("productId"), req.getString("productName"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			if("YD".equals(req.getString("source"))){
				Product product = productService.get(req.getString("productId"));
				if (product != null) {
					if("0".equals(product.getIsDl())){
						res.setResultNote("该商品不能被代理！");
						return res;
					}
				}
			}
			String goodssign =" ";
			if("PDD".equals(req.getString("source"))){
					if(!isBlank(req.getString("goodssign"))){
						goodssign=req.getString("goodssign");
					}
			}

			//自动取消未付款的增选产品订单
			List<Map<String,Object>> data = proxyProductService.executeSelectSql("SELECT order_state,uid,id FROM t_proxy_product where uid='"+req.getString("uid")+"' AND order_state='0'");
			if (data != null && !data.isEmpty()) {
				for (Map<String, Object> map : data) {
					String state = map.get("order_state").toString();
					String orderno = map.get("id").toString();
					if ("0".equals(state)) {
						proxyProductService.executeUpdateSql("UPDATE t_proxy_product SET order_state = '2' WHERE id = '" + orderno + "' AND order_state = '0'");
						List<WohuiEntity> list1 = Lists.newArrayList();
						list1.add(new WohuiEntity("OrderNO",  map.get("id").toString()));
						JSONObject object = WohuiUtils.send(WohuiUtils.MSMGoodsCancel, list1);
						if (!"0000".equals(object.getString("respCode"))) {
							logger.error("取消增选产品订单号"+orderno+"失败：" + object.getString("respMsg"));
						}
					}
				}
			}
			// 判断该产品是否被代理
			if (proxyProductService.exist(req.getString("province"), req.getString("city"), req.getString("area"), req.getString("source"), req.getString("productId"))) {
				res.setResultNote("此产品在该区域已被代理");
				return res;
			}
			String fee = "2";// 服务费
				List<ProxyPrice> proxyPriceList = proxyPriceService.findList(new ProxyPrice());
				if (!proxyPriceList.isEmpty()) {
					String pickPrice = proxyPriceList.get(0).getPickPrice();
					if (StringUtils.isNotBlank(pickPrice)) {
						fee = pickPrice;
					}
				}
				// 调用三方会员系统
				List<WohuiEntity> list2 = Lists.newArrayList();
				list2.add(new WohuiEntity("UGUID", req.getUid()));
				JSONObject object5 = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, list2);
				if (!"0000".equals(object5.getString("respCode"))) {
					res.setResultNote("获取失败："+object5.getString("respMsg"));
					return res;
				}
				JSONArray data3 = object5.getJSONArray("data");
				JSONObject obj = data3.getJSONObject(0);
				//单品代理增选
				if(obj.getIntValue("C_GoodsFreeCanNum") > obj.getIntValue("C_GoodsFreeHasNum") || obj.getIntValue("C_GoodsGiveNum") > 0 || obj.getIntValue("C_GoodsMSMFreeNum") > 0 || obj.getIntValue("C_PCANumTCGive") > 0 || obj.getIntValue("C_PCANumXFQGive") > 0){
					fee = "0.00";
				}


			String orderId = OrderNumPrefix.proxyProductOrder + IdGen.getOrderNo();
			ProxyProduct proxyProduct = new ProxyProduct();
			proxyProduct.setIsNewRecord(true);
			proxyProduct.setId(orderId);
			proxyProduct.setMember(member);
			proxyProduct.setProductId(req.getString("productId"));
			String productName = StringUtils.replace(req.getString("productName"), " ", "");
			proxyProduct.setGoodssign(goodssign);
			proxyProduct.setProductName(productName);
			proxyProduct.setProductImage(req.getString("productImage"));
			proxyProduct.setType(req.getString("source"));
			proxyProduct.setProvince(req.getString("province"));
			proxyProduct.setCity(req.getString("city"));
			proxyProduct.setArea(req.getString("area"));
			proxyProduct.setProxyId(req.getString("proxyId"));
			proxyProduct.setState("0");
			proxyProduct.setFee(fee);
			if("0.00".equals(proxyProduct.getFee())){
				proxyProduct.setOrderState("1");
			}else{
				proxyProduct.setOrderState("0");
			}
			proxyProductService.insert(proxyProduct);
			if("0.00".equals(proxyProduct.getFee())){
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("OrderNO", proxyProduct.getId()));
				JSONObject object = WohuiUtils.send(WohuiUtils.MSMGoodsOpen, list);
				if (!"0000".equals(object.getString("respCode"))) {
					logger.error("开通代理产品失败：" + object.getString("respMsg"));
					WohuiUtils.send(WohuiUtils.MSMGoodsCancel, list);//开通失败取消申请
					res.setResultNote("开通代理产品失败："+object.getString("respMsg"));
					return res;
				}
			}

			res.put("orderId", orderId);
			res.put("amount", fee);
			res.setResult("0");
			res.setResultNote("提交成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
			res.setResultNote(e.getMessage());
		}
		return res;
	}

	/**
	 * 获取用户代理的产品
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/findProxyProductListById")
	@ResponseBody
	public ResJson findProxyProductListById(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("proxyId"))) {
				res.setResultNote("代理ID不能为空");
				return res;
			}

			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("MSMGUID", req.getString("proxyId")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.GetMSMGoods, list);
			if (!"0000".equals(jsonObject.getString("respCode"))) {
				res.setResultNote(jsonObject.getString("respMsg"));
				return res;
			}
			res.setTotalPage(jsonObject.getIntValue("totalCount"));
			JSONArray array = jsonObject.getJSONArray("data");
			if (array != null && !array.isEmpty()) {
				for (int i = 0; i < array.size(); i++) {
					JSONObject data = array.getJSONObject(i);
					Map<String, String> map = Maps.newHashMap();
					map.put("proxyId", data.getString("MSMG_MSMGUID"));
					map.put("msmgguid", data.getString("MSMG_GUID"));
					map.put("province", data.getString("MSMG_Province"));
					map.put("city", data.getString("MSMG_City"));
					map.put("area", data.getString("MSMG_District"));
					map.put("source", data.getString("MSMG_Source"));
					map.put("productId", data.getString("MSMG_GoodsID"));
					map.put("productName", data.getString("MSMG_GoodsName"));
					map.put("productImage", data.getString("MSMG_ImgUrl"));
					map.put("fee", data.getString("MSMG_Fee"));
					map.put("time", data.getString("MSMG_Time"));
					map.put("status", data.getString("MSMG_Status"));
					dataList.add(map);
				}
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 查询用户云店铺信息（资格）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/getProxyListById")
	@ResponseBody
	public ResJson getProxyListById(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}

			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getUid()));
			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.GetMSM, list);
			if (!"0000".equals(jsonObject.getString("respCode"))) {
				res.setResultNote(jsonObject.getString("respMsg"));
				return res;
			}

			JSONArray array = jsonObject.getJSONArray("data");
			if (array != null && !array.isEmpty()) {
				List<List<Integer>> pdList = Lists.newArrayList();
				List<PickDay> pickDayList = pickDayService.findList(new PickDay());
				for (PickDay pickDay : pickDayList) {
					List<Integer> dateList = Lists.newArrayList();
					String[] dates = pickDay.getDates().split(",");
					for (String date : dates) {
						dateList.add(Integer.parseInt(date));
					}
					pdList.add(dateList);
				}
				for (int i = 0; i < array.size(); i++) {
					JSONObject data = array.getJSONObject(i);
					// 单品代理状态（10待付款，20 已付款，30 已签收，40 已开通，50 已取消）
					if ("40".equals(data.getString("MSM_Status"))) {
						Map<String, String> map = Maps.newHashMap();
						map.put("proxyId", data.getString("MSM_GUID"));
						map.put("realname", data.getString("MSM_RealName"));
						map.put("phone", data.getString("MSM_Phone"));
						map.put("orderNo", data.getString("MSM_OrderNO"));
						map.put("storeCode", data.getString("MSM_GYSCode"));
						map.put("applyTime", data.getString("MSM_ApplyTime"));
						map.put("openTime", data.getString("MSM_OpenTime"));
						map.put("expTime", data.getString("MSM_ExpTime"));
						map.put("fee", data.getString("MSM_Fee"));
						map.put("lastTime", data.getString("MSM_LAddTime"));
						map.put("remark", data.getString("MSM_Remark"));
						map.put("mcode", data.getString("MSM_MCode"));
						//新增
						map.put("type", data.getString("MSM_Type"));
						map.put("goodsnum", data.getString("MSM_GoodsNum"));
						map.put("msm_role", data.getString("MSM_Role"));
						String pickDay = "0";
						Date openTime = DateUtils.parseDate(data.getString("MSM_OpenTime"));
						Calendar cal = Calendar.getInstance();
						cal.setTime(openTime);
						int day = cal.get(Calendar.DAY_OF_MONTH);
						int today = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
						for (List<Integer> dateList : pdList) {
							if (dateList.contains(day) && dateList.contains(today)) {
								pickDay = "1";
								break;
							}
						}
						map.put("pickDay", pickDay);
						dataList.add(map);
					}
				}
			}

			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 查询用户云店铺单个信息（资格）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/getProxyFirstById")
	@ResponseBody
	public ResJson getProxyFirstById(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getUid()));
			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.GetMSM, list);
			if (!"0000".equals(jsonObject.getString("respCode"))) {
				res.setResultNote(jsonObject.getString("respMsg"));
				return res;
			}
			JSONArray array = jsonObject.getJSONArray("data");
			if (array == null && array.isEmpty()) {
				res.setResultNote("未获取该会员的代理信息");
				return res;
			}
			JSONObject data = array.getJSONObject(0);
			res.put("proxyId", data.getString("MSM_GUID"));
			res.put("expTime", data.getString("MSM_ExpTime"));
			res.put("fee", data.getString("MSM_Fee"));
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增2022/05/29
	 *云店铺-开通
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCFMOpen")
	@ResponseBody
	public ResJson ForCFMOpen(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			String cfmMargin = "500.00";
			String monthprice = "60.00";
			List<ProxyPrice> list = proxyPriceService.findList(new ProxyPrice());
			if (!list.isEmpty()) {
				cfmMargin = list.get(0).getCfmMargin();
				monthprice = list.get(0).getMonthprice();

			}
			String orderId ="CFM" + IdGen.getOrderNo();//支付单号
			Cfm o = new Cfm();
			o.setId(orderId);
			o.setGoodsnum("1");
			o.setCreateDate(new Date());
			o.setMoney(cfmMargin);
			o.setMonth("12");
			o.setMember(new Member(req.getString("uid")));
			o.setState("0");
			cfmMapper.insert(o);
			res.put("money",o.getMoney());
			res.put("orderno",o.getId());
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 云店铺产品-列表 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCFMGoodsList")
	@ResponseBody
	public ResJson ForCFMGoodsList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			JSONObject object = WohuiUtils.send(WohuiUtils.CFMGoodsList, list);
			JSONArray array = object.getJSONArray("data");
			BigDecimal num = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//
			int renewNum  = (int) num.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
			res.setTotalPage(renewNum);
			res.put("rowsCount",object.getString("rowsCount"));
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {

				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 云店铺产品-添加 接口
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCFMGoodsAdd")
	@ResponseBody
	public ResJson ForCFMGoodsAdd(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("提交失败");
		try {
			if (isBlank(req.getUid(), req.getString("source"), req.getString("productId"), req.getString("productName"), req.getString("productImage"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			if (isBlank(req.getString("price"))){
				res.setResultNote("商品价格不能为空");
				return res;
			}
			if (isBlank(req.getString("coupon"))){
				res.setResultNote("优惠券金额不能为空");
				return res;
			}
			if (isBlank(req.getString("point"))){
				res.setResultNote("铜板不能为空");
				return res;
			}

			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			if("YD".equals(req.getString("source"))){
				Product product = productService.get(req.getString("productId"));
				if (product != null) {
					if("0".equals(product.getIsDl())){
						res.setResultNote("该商品不能被代理！");
						return res;
					}
				}
			}
			String goodssign =" ";
			if("PDD".equals(req.getString("source"))){
				if(!isBlank(req.getString("goodssign"))){
					goodssign=req.getString("goodssign");
				}
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getUid()));
			list.add(new WohuiEntity("Source", req.getString("source")));
			list.add(new WohuiEntity("GoodsID", req.getString("productId")));
			list.add(new WohuiEntity("GoodsSign",req.getString("goodssign")));
			list.add(new WohuiEntity("GoodsName", req.getString("productName"),false));
			list.add(new WohuiEntity("ImgUrl", req.getString("productImage"),false));
			list.add(new WohuiEntity("Price", req.getString("price")));
			list.add(new WohuiEntity("Coupon", req.getString("coupon")));
			list.add(new WohuiEntity("PTFL", req.getString("point")));
			JSONObject object = WohuiUtils.send(WohuiUtils.CFMGoodsAdd, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("开通代理产品失败："+object.getString("respMsg"));
				return res;
			}
			res.setResult("0");
			res.setResultNote("提交成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
			res.setResultNote(e.getMessage());
		}
		return res;
	}
	/**
	 * 云店铺产品-删除 接口  2022/6/17
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCFMGoodsDelete")
	@ResponseBody
	public ResJson ForCFMGoodsDelete(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("cfmgguid"))) {
				res.setResultNote("请确认编号");
				return res;
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CFMGGUID", req.getString("cfmgguid")));
			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.CFMGoodsDelete, list);
			if (!"0000".equals(jsonObject.getString("respCode"))) {
				res.setResultNote(jsonObject.getString("respMsg"));
				return res;
			}
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 云店铺产品-置顶  2022/6/17
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCFMGoodsSetTop")
	@ResponseBody
	public ResJson ForCFMGoodsSetTop(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("cfmgguid"))) {
				res.setResultNote("请确认编号");
				return res;
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CFMGGUID", req.getString("cfmgguid")));
			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.CFMGoodsSetTop, list);
			if (!"0000".equals(jsonObject.getString("respCode"))) {
				res.setResultNote(jsonObject.getString("respMsg"));
				return res;
			}
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 云店铺产品-排序  2022/6/17
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCFMGoodsSetSort")
	@ResponseBody
	public ResJson ForCFMGoodsSetSort(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("cfmgguid"))) {
				res.setResultNote("请确认编号");
				return res;
			}
			if (StringUtils.isBlank(req.getString("sort"))) {
				res.setResultNote("请确认排序号");
				return res;
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CFMGGUID", req.getString("cfmgguid")));
			list.add(new WohuiEntity("Sort", req.getString("sort")));
			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.CFMGoodsSetSort, list);
			if (!"0000".equals(jsonObject.getString("respCode"))) {
				res.setResultNote(jsonObject.getString("respMsg"));
				return res;
			}
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 云店铺产品-设置销售标签  2022/6/17
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCFMGoodsSetTag")
	@ResponseBody
	public ResJson ForCFMGoodsSetTag(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("cfmgguid"))) {
				res.setResultNote("请确认编号");
				return res;
			}
			if (StringUtils.isBlank(req.getString("tag"))) {
				res.setResultNote("请输入标签");
				return res;
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CFMGGUID", req.getString("cfmgguid")));
			list.add(new WohuiEntity("Tag", req.getString("tag")));
			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.CFMGoodsSetTag, list);
			if (!"0000".equals(jsonObject.getString("respCode"))) {
				res.setResultNote(jsonObject.getString("respMsg"));
				return res;
			}
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 跳转出行页面
	 *
	 * @param req
	 * @param response
	 * @return
	 */
	@PostMapping("/toTravel")
	@ResponseBody
	public ResJson toTravel(@RequestBody ReqJson req, HttpServletResponse response) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			String authInfo = ZhongTaiUtil.getAuthInfo(member.getPhone(), "1".equals(req.getString("client")) ? "WX" : "WEB_M");
			response.sendRedirect(ZhongTaiUtil.getUrl(authInfo, req.getString("type")));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		res.setResult("0");
		res.setResultNote("获取成功");
		return res;
	}

	/**
	 * 获取出行认证信息
	 *
	 * @param req
	 * @param response
	 * @return
	 */
	@PostMapping("/getAuthInfo")
	@ResponseBody
	public ResJson getAuthInfo(@RequestBody ReqJson req, HttpServletResponse response) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			String authInfo = ZhongTaiUtil.getAuthInfo(member.getPhone(), "1".equals(req.getString("client")) ? "WX" : "WEB_M");
			res.put("authinfo", authInfo);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 消息详情
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/msgDetail")
	@ResponseBody
	public ResJson msgDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("msgId"))) {
				res.setResultNote("消息ID不能为空");
				return res;
			}

			Msg msg = msgService.get(req.getString("msgId"));
			if (msg == null) {
				res.setResultNote("该消息不存在或被删除");
				return res;
			}

			res.put("title", msg.getTitle());
			res.put("createDate", DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(msg.getCreateDate()));
			res.put("content", msg.getContent());

			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 优惠券订单核销
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/confirmCouponOrder")
	@ResponseBody
	public ResJson confirmCouponOrder(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败");
		try {
			if (isBlank(req.getString("orderId"), req.getString("shopId"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			CouponOrder couponOrder = couponOrderService.get(req.getString("orderId"));
			if (couponOrder == null || !req.getString("shopId").equals(couponOrder.getShop().getId())) {
				res.setResultNote("订单不存在");
				return res;
			}
			if (!"1".equals(couponOrder.getState())) {
				res.setResultNote("订单状态异常，不能核销");
				return res;
			}
			couponOrder.setState("2");
			couponOrder.setUseDate(new Date());
			couponOrderService.hexiao(couponOrder);

			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 实体店优惠券上架/下架
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/editCouponState")
	@ResponseBody
	public ResJson editCouponState(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("id"), req.getString("shopId"), req.getString("type"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			ShopCoupon shopCoupon = shopCouponService.get(req.getString("id"));
			if (shopCoupon == null || !shopCoupon.getShop().getId().equals(req.getString("shopId"))) {
				res.setResultNote("优惠券不存在");
				return res;
			}

			// 0-下架，1-上架
			if ("1".equals(req.getString("type"))) {
				shopCoupon.setState("1");
			} else {
				shopCoupon.setState("0");
			}
			shopCouponService.save(shopCoupon);
			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 店铺订单退款审核
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/factoryOrderRefundAuth")
	@ResponseBody
	public ResJson factoryOrderRefundAuth(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败");
		try {
			if (isBlank(req.getString("factoryId"), req.getString("orderId"), req.getString("type"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			// 判断订单类型
			if (StringUtils.startsWithIgnoreCase(req.getString("orderId"), OrderNumPrefix.groupOrder)) {// 拼团订单
				GroupOrder order = groupOrderService.get(req.getString("orderId"));
				if (order == null || !order.getStore().getId().equals(req.getString("factoryId"))) {
					res.setResultNote("订单不存在");
					return res;
				}
				if (!"6".equals(order.getState())) {
					res.setResultNote("订单状态异常，只能操作退款中的订单");
					return res;
				}
				groupOrderService.refund(order, req.getString("type"));
			} else {// 云店普通订单
				ProductOrder order = productOrderService.get(req.getString("orderId"));
				if (order == null || !order.getStore().getId().equals(req.getString("factoryId"))) {
					res.setResultNote("订单不存在");
					return res;
				}
				if (!"6".equals(order.getState())) {
					res.setResultNote("订单状态异常，只能操作退款中的订单");
					return res;
				}

				productOrderService.refund(order, req.getString("type"));
			}

			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			res.setResultNote(e.getMessage());
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 店铺订单发货
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/factoryOrderSend")
	@ResponseBody
	public ResJson factoryOrderSend(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败");
		try {
			if (isBlank(req.getString("factoryId"), req.getString("orderId"), req.getString("deliveryId"), req.getString("expressNo"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			Delivery delivery = deliveryService.get(req.getString("deliveryId"));
			if (delivery == null) {
				res.setResultNote("所选物流不存在");
				return res;
			}

			// 判断订单类型
			if (StringUtils.startsWithIgnoreCase(req.getString("orderId"), OrderNumPrefix.groupOrder)) {// 拼团订单
				GroupOrder order = groupOrderService.get(req.getString("orderId"));
				if (order == null || !order.getStore().getId().equals(req.getString("factoryId"))) {
					res.setResultNote("订单不存在");
					return res;
				}
				if (!"1".equals(order.getState())) {
					res.setResultNote("订单状态异常，只能操作待发货订单");
					return res;
				}

				order.setState("2");
				order.setExpressCode(delivery.getCode());
				order.setExpressName(delivery.getCorp());
				order.setExpressNo(req.getString("expressNo"));
				order.setSendDate(new Date());
				order.setExpireDate(DateUtils.addDays(new Date(), 15));
				groupOrderService.send(order);


			} else {// 云店普通订单
				ProductOrder order = productOrderService.get(req.getString("orderId"));
				if (order == null || !order.getStore().getId().equals(req.getString("factoryId"))) {
					res.setResultNote("订单不存在");
					return res;
				}
				if (!"1".equals(order.getState())) {
					res.setResultNote("订单状态异常，只能操作待发货订单");
					return res;
				}
				order.setState("2");
				order.setExpressCode(delivery.getCode());
				order.setExpressName(delivery.getCorp());
				order.setExpressNo(req.getString("expressNo"));
				order.setSendDate(new Date());
				order.setExpireDate(DateUtils.addDays(new Date(), 15));
				productOrderService.send(order);
			}

			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 物流公司列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/getDeliveryList")
	@ResponseBody
	public ResJson getDeliveryList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			Delivery delivery = new Delivery();
			delivery.setState("0");
			List<Delivery> list = deliveryService.findList(delivery);
			if (!list.isEmpty()) {
				for (Delivery delivery2 : list) {
					Map<String, String> map = Maps.newHashMap();
					map.put("deliveryId", delivery2.getId());
					map.put("deliveryName", delivery2.getCorp());
					dataList.add(map);
				}
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 支付宝授权登录获取信息
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/getAliUserInfoByCode")
	@ResponseBody
	public ResJson getAliUserInfoByCode(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("code"))) {
				res.setResultNote("授权码不能为空");
				return res;
			}
			res.putAll(AlipayUtils.getAccessTokenAndUserId(req.getString("code")));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 单品代理更换淘客商品
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/addLMProduct")
	@ResponseBody
	public ResJson addLMProduct(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("提交失败");
		try {
			if (isBlank(req.getUid(), req.getString("code"), req.getString("type"), req.getString("productId"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			ProxyOrder proxyOrder = new ProxyOrder();
			proxyOrder.setMember(new Member(req.getUid()));
			proxyOrder.setCode(req.getString("code"));
			List<ProxyOrder> list = proxyOrderService.findList(proxyOrder);
			if (list == null || list.isEmpty()) {
				res.setResultNote("代理不存在");
				return res;
			}
			ProxyOrder order = list.get(0);

			// 判断优惠券过期数量
			String count = proxyProductService.executeGetSql("SELECT COUNT(a.id) FROM t_proxy_product a WHERE a.`code` = '" + req.getString("code") + "' AND a.state = '0' AND a.end_date > NOW()").toString();
			if (!"0".equals(count)) {
				res.setResultNote("代理中的产品不存在已失效");
				return res;
			}

			// 判断商品是否被代理
			String num = apiService.getProxyProductCountByProductId(req.getString("productId"), req.getString("type"), order.getProvince(), order.getCity(), order.getArea());
			if (!"0".equals(num)) {
				res.setResultNote("此商品在该区域已被代理");
				return res;
			}

			// 获取商品信息 联盟商品类型 1淘客 2京东 3拼多多
			if ("1".equals(req.getString("type"))) {
				Map<String, String> params = Maps.newHashMap();
				params.put("tao_id", req.getString("productId"));
				JSONObject object = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_detail, params);
				if (!"200".equals(object.getString("status"))) {
					res.setResultNote(object.getString("content"));
					return res;
				}
				JSONArray jsonArray = object.getJSONArray("content");
				JSONObject data = jsonArray.getJSONObject(0);

				ProxyProduct proxyProduct = new ProxyProduct();
				proxyProduct.setCode(req.getString("code"));
				proxyProduct.setProductId(data.getString("tao_id"));
				proxyProduct.setProductName(data.getString("title"));
				proxyProduct.setProductImage(data.getString("pict_url"));
				proxyProduct.setProductPrice(data.getString("quanhou_jiage"));
				proxyProduct.setProductPoint(data.getString("tkfee3"));
				proxyProduct.setType("1");
				proxyProduct.setState("0");
				proxyProduct.setEndDate(DateUtils.parseDate(data.getString("coupon_end_time")));
				proxyProductService.save(proxyProduct);
			} else if ("2".equals(req.getString("type"))) {
				// 待完成

			} else if ("3".equals(req.getString("type"))) {
				// 待完成

			} else {
				return res;
			}

			res.setResult("0");
			res.setResultNote("提交成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 根据手机号查询赠送单品代理资格
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/findMsmCouponListByPhone")
	@ResponseBody
	public ResJson findMsmCouponListByPhone(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("phone"))) {
				res.setResultNote("手机号不能为空");
				return res;
			}

			Member member = new Member();
			member.setPhone(req.getString("phone"));
			List<Member> memberList = memberService.findList(member);
			if (memberList == null || memberList.isEmpty()) {
				res.setResultNote("该手机号不存在");
				return res;
			}
			member = memberList.get(0);
			res.put("userId", member.getId());

			int ms_count = 0;
			int ts_count = 0;

			List<WohuiEntity> entityList = Lists.newArrayList();
			entityList.add(new WohuiEntity("CardGUID", member.getId()));
			entityList.add(new WohuiEntity("Type", "ALL"));
			WohuiEntity way = new WohuiEntity("Way", "MS");
			entityList.add(way);
			JSONObject msObj = WohuiUtils.send(WohuiUtils.MSMCouponList, entityList);
			if ("0000".equals(msObj.getString("respCode"))) {
				JSONArray data = msObj.getJSONArray("data");
				if (data != null && !data.isEmpty()) {
					ms_count = data.size();
					JSONObject object = data.getJSONObject(0);

					res.put("ms_couponId", object.getString("MSMC_GUID"));
					res.put("ms_unionId", object.getString("MSMC_UnionGUID"));
				}
			}
			entityList.remove(way);
			entityList.add(new WohuiEntity("Way", "TS"));
			JSONObject tsObj = WohuiUtils.send(WohuiUtils.MSMCouponList, entityList);
			if ("0000".equals(tsObj.getString("respCode"))) {
				JSONArray data = tsObj.getJSONArray("data");
				if (data != null && !data.isEmpty()) {
					ts_count = data.size();
					JSONObject object = data.getJSONObject(0);

					res.put("ts_couponId", object.getString("MSMC_GUID"));
					res.put("ts_unionId", object.getString("MSMC_UnionGUID"));
				}
			}

			res.put("ms_count", ms_count);
			res.put("ts_count", ts_count);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 分享绑定上下级关系
	 * 修改版wind
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/newbindRelation")
	@ResponseBody
	public ResJson newbindRelation(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
//		ProductOrder productOrder = productOrderService.get(req.getString("orderId"));
//		if (productOrder != null) {
//			productOrderService.pay(productOrder);
//		}
		res.setResultNote("操作失败");
		try {
			if(req.getString("inviteId").equals(req.getUid())){
				res.setResult("1");
				res.setResultNote("操作失败,账户或邀请人不能相同");
				return res;
			}
			if (req.getUid() != null && req.getString("inviteId") != null) {
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("CardGUID", req.getUid()));
				list.add(new WohuiEntity("SenderGUID", req.getString("inviteId")));
				JSONObject object = WohuiUtils.send(WohuiUtils.ChangeSender, list);
				if ("0000".equals(object.getString("respCode"))) {
					memberService.updateInvite(req.getUid(), req.getString("inviteId"));
					res.setResult("0");
					res.setResultNote("操作成功");
				} else {
					logger.error("更换邀请人失败：" + object.getString("respMsg"));
					res.setResult("1");
					res.setResultNote(object.getString("respMsg"));
				}
			} else {
				res.setResult("1");
				res.setResultNote("操作失败,账户或邀请人不存在");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 全国厂家总店列表
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForGetNFHGoodsAllList")
	@ResponseBody
	public ResJson ForGetNFHGoodsAllList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (!isBlank(req.getUid())) {
				// 调用三方接口
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("CardGUID", req.getUid()));
				list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
				list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
				JSONObject object = WohuiUtils.send(WohuiUtils.NFHGoodsAllList, list);
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("获取失败：" + object.getString("respMsg"));
				} else {
					JSONArray array = object.getJSONArray("data");
					BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//付款时的手续费
					int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
					res.setTotalPage(renewNum);
					res.put("rowsCount",object.getString("rowsCount"));
					res.put("totalCount",object.getString("totalCount"));
					List<Map<String, Object>> dataList = Lists.newArrayList();
					if(array != null && !array.isEmpty()){
						List<JSONObject> list2 = JSONArray.parseArray(array.toJSONString(), JSONObject.class);
						Collections.reverse(list2);
						// list转JSONArray
						JSONArray dataArray = JSONArray.parseArray(list2.toString());
						res.setDataList(dataArray);
					}else{
						res.setDataList(dataList);
					}
					res.setResult("0");
					res.setResultNote("获取成功");
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 全国厂家总店产品添加
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForNFHGoodsAdd")
	@ResponseBody
	public ResJson ForNFHGoodsAdd(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("提交失败");
		try {
			if (isBlank(req.getUid(), req.getString("source"), req.getString("productId"), req.getString("productName"), req.getString("productImage"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			if("YD".equals(req.getString("source"))){
				Product product = productService.get(req.getString("productId"));
				if (product != null) {
					if("0".equals(product.getIsDl())){
						res.setResultNote("该商品不能被代理！");
						return res;
					}
				}
			}
			String goodssign =" ";
			if("PDD".equals(req.getString("source"))){
				if(!isBlank(req.getString("goodssign"))){
					goodssign=req.getString("goodssign");
				}
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getUid()));
			list.add(new WohuiEntity("Source", req.getString("source")));
			list.add(new WohuiEntity("GoodsID", req.getString("productId")));
			list.add(new WohuiEntity("GoodsSign", goodssign ));
			list.add(new WohuiEntity("GoodsName", req.getString("productName"), false));
			list.add(new WohuiEntity("GoodsImgUrl", req.getString("productImage"), false));
			JSONObject object = WohuiUtils.send(WohuiUtils.NFHGoodsAdd, list);
			if (!"0000".equals(object.getString("respCode"))) {
				logger.error("全国厂家总店产品申请失败：" + object.getString("respMsg"));
				res.setResultNote("全国厂家总店产品申请失败："+object.getString("respMsg"));
				return res;
			}
			res.setResult("0");
			res.setResultNote("提交成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
			res.setResultNote(e.getMessage());
		}
		return res;
	}
	/**
	 * 全国厂家总店产品更换接口wind
	 * @param req
	 * @return
	 */
	@PostMapping("/ForNFHGoodsChange")
	@ResponseBody
	public ResJson ForNFHGoodsChange(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("productId"))) {
				res.setResultNote("商品ID不能为空！");
				return res;
			}
			String goodssign =" ";
			if("PDD".equals(req.getString("source"))){
				if (!StringUtils.isBlank(req.getString("goodssign"))) {
					goodssign=req.getString("goodssign");
				}
			}
			if (isBlank(req.getString("nfhgguid"), req.getString("source"), req.getString("productName"), req.getString("productImage"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("NFHGGUID", req.getString("nfhgguid")));
			list.add(new WohuiEntity("Source", req.getString("source")));
			list.add(new WohuiEntity("GoodsID", req.getString("productId")));
			list.add(new WohuiEntity("GoodsSign", goodssign));
			list.add(new WohuiEntity("GoodsName", req.getString("productName"), false));
			list.add(new WohuiEntity("GoodsImgUrl", req.getString("productImage"), false));
			JSONObject object = WohuiUtils.send(WohuiUtils.NFHGoodsChange, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setDataList(array);
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 全国厂家总店-可选货数量接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForNFHCanXHNum")
	@ResponseBody
	public ResJson ForNFHCanXHNum(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getUid()));
			JSONObject object = WohuiUtils.send(WohuiUtils.NFHCanXHNum, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.put("CanXHNum",object.getIntValue("CanXHNum"));
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 城市合伙人-空开 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCFDMEmptyOpen")
	@ResponseBody
	public ResJson ForCFDMEmptyOpen(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("ncguid"))) {
				res.setResultNote("申请的类型编号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("province"))) {
				res.setResultNote("省份不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("城市不能为空！");
				return res;
			}

			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("NCGUID", req.getString("ncguid")));
			list.add(new WohuiEntity("Province", req.getString("province")));
			list.add(new WohuiEntity("City", req.getString("city")));
			list.add(new WohuiEntity("District", req.getString("district"),false));
			JSONObject object = WohuiUtils.send(WohuiUtils.CFDMEmptyOpen, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增城市合伙人2022/3/4 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCFDMOpen")
	@ResponseBody
	public ResJson ForCFDMOpen(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("province"))) {
				res.setResultNote("省份不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("城市不能为空！");
				return res;
			}

			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getUid()));
			list.add(new WohuiEntity("Province", req.getString("province")));
			list.add(new WohuiEntity("City", req.getString("city")));
			list.add(new WohuiEntity("District", req.getString("district"),false));
			JSONObject object = WohuiUtils.send(WohuiUtils.CFDMOpen, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 城市合伙人-可申请类型列表接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForNFHCFDMList")
	@ResponseBody
	public ResJson ForNFHCFDMList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			JSONObject object = WohuiUtils.send(WohuiUtils.NFHCFDMList, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setDataList(array);
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 云店铺销售列表接口
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForGetCSSaleLog")
	@ResponseBody
	public ResJson ForGetCSSaleLog(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (!isBlank(req.getUid())) {
				// 调用三方接口
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("CardGUID", req.getUid()));
				list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
				list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
				JSONObject object = WohuiUtils.send(WohuiUtils.CSSaleLog, list);
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("获取失败：" + object.getString("respMsg"));
				} else {
					JSONArray array = object.getJSONArray("data");
					BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//付款时的手续费
					int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
					res.setTotalPage(renewNum);
					res.put("rowsCount",object.getString("rowsCount"));
					List<Map<String, Object>> dataList = Lists.newArrayList();
					if(array != null && !array.isEmpty()){
						res.setDataList(array);
					}else{
						res.setDataList(dataList);
					}
					res.setResult("0");
					res.setResultNote("获取成功");
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
    /**
     * 批发云店铺产品-列表(去重后)
     *
     * @param req
     * @return
     */
    @PostMapping("/ForGetMSMGoodsMyList")
    @ResponseBody
    public ResJson ForGetMSMGoodsMyList(@RequestBody ReqJson req) {
        ResJson res = new ResJson();
        res.setResultNote("获取失败");
		try {
        if (!isBlank(req.getUid())) {
            // 调用三方接口
            List<WohuiEntity> list = Lists.newArrayList();
            list.add(new WohuiEntity("CardGUID", req.getUid()));
            list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
            list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			JSONObject object = WohuiUtils.send(WohuiUtils.GetMSMGoodsMyList, list);
            if (!"0000".equals(object.getString("respCode"))) {
                res.setResultNote("获取失败：" + object.getString("respMsg"));
            } else {
                JSONArray array = object.getJSONArray("data");
				BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//付款时的手续费
				int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
				res.setTotalPage(renewNum);
                res.put("rowsCount",object.getString("rowsCount"));
				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
                res.setResult("0");
                res.setResultNote("获取成功");
            }
        }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return res;
    }

	/**
	 * 批发云店铺产品-列表(去重后)
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/ForGetMSMGoodsAllList")
	@ResponseBody
	public ResJson ForGetMSMGoodsAllList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (!isBlank(req.getUid())) {
				String area ="";
				if(!isBlank(req.getString("area"))){
					area =req.getString("area");
				}
				// 调用三方接口
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("CardGUID", req.getUid()));
				list.add(new WohuiEntity("Area", area));
				list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
				list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
				JSONObject object = WohuiUtils.send(WohuiUtils.GetMSMGoodsAllList, list);
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("获取失败：" + object.getString("respMsg"));
				} else {
					JSONArray array = object.getJSONArray("data");
//					Double number = object.getIntValue("totalCount") / req.getPageSize();
					BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//付款时的手续费
					int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
//					int renewNum = (int)Math.ceil(number);
					res.setTotalPage(renewNum);
					res.put("rowsCount",object.getString("rowsCount"));
					res.put("totalCount",object.getString("totalCount"));
					List<Map<String, Object>> dataList = Lists.newArrayList();
					if(array != null && !array.isEmpty()){
						res.setDataList(array);
					}else{
						res.setDataList(dataList);
					}
					res.setResult("0");
					res.setResultNote("获取成功");
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 判断是否可更换代理产品
	 *
	 * @param req
	 * @return
	 */
	@PostMapping({"/IsMSMChange"})
	@ResponseBody
	public ResJson IsMSMChange(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
		if (StringUtils.isBlank(req.getString("goodsid"))) {
			res.setResultNote("商品ID不能为空！");
			return res;
		}
		if (StringUtils.isBlank(req.getString("source"))) {
			res.setResultNote("商品来源不能为空！");
			return res;
		}
		//云店商品是否上架判断
		if("YD".equals(req.getString("source"))){
			Product product = productService.get(req.getString("goodsid"));
			if (product != null && "0".equals(product.getState())) {
//			    String Point = product.getPoint();
//			    if(Double.parseDouble(Point) >= 0.00){
                    res.setResultNote("该云店商品正在上架中，不可更换！");
                    return res;
//                }
			}
		}else if("ALI".equals(req.getString("source"))){
			Map<String, String> params = Maps.newHashMap();
			params.put("tao_id", req.getString("goodsid"));
			JSONObject object = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_detail, params);
			logger.debug("折淘客返回数据：" + object.toString());
			if (!"301".equals(object.getString("status"))) {
				res.setResultNote("该阿里商品正在上架中，不可更换！");
				return res;
			}
		}else if("JD".equals(req.getString("source"))){
			Map<String, String> params = Maps.newHashMap();
			params.put("skuIds", req.getString("goodsid"));
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getJdUnionItems, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if ("200".equals(jsonObject.getString("code"))){
				JSONArray dataArray = jsonObject.getJSONObject("data").getJSONArray("list");
				List<Map<String, Object>> categoryList = Lists.newArrayList();
				if (!dataArray.isEmpty()) {
					for(int i = 0; i < dataArray.size(); ++i) {
						JSONObject c = dataArray.getJSONObject(i);
						JSONObject data = c.getJSONObject("commissionInfo");
						categoryList.add(data);
					}
					Object commissionShare = ((Map)categoryList.get(0)).get("commissionShare");
					if (!this.isBlank(String.valueOf(commissionShare))) {
						res.setResultNote("该京东商品正在上架中，不可更换！");
						return res;
					}
				}
			}
		}else if("PDD".equals(req.getString("source"))){
//		拼多多商品判断
			Map<String, String> params = Maps.newHashMap();
			params = Maps.newHashMap();
			params.put("goods_sign", req.getString("goodsid"));
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getGoodsDetailInfo, params);
			this.logger.debug("喵有券返回数据：" + jsonObject.toString());
			if ("200".equals(jsonObject.getString("code")) ) {
				if (!jsonObject.getJSONArray("data").isEmpty()) {
					String rate = jsonObject.getJSONArray("data").getJSONObject(0).getString("promotion_rate");
					if (!this.isBlank(rate)) {
						res.setResultNote("该拼多多商品正在上架中，不可更换！");
						return res;
					}
				}
			}
		}
		res.setResult("0");
		res.setResultNote("获取成功");

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

    /**
     * 扶贫-贫困户列表接口
     * @param req
     * @return
     */
    @PostMapping("/ForHP_UserList")
    @ResponseBody
    public ResJson ForHP_UserList(@RequestBody ReqJson req) {
        ResJson res = new ResJson();
        res.setResultNote("获取失败");
        try {
            if (StringUtils.isBlank(req.getString("areaId"))) {
                res.setResultNote("区县ID不能为空！");
                return res;
            }
            Area area = areaService.get(req.getString("areaId"));
            if (area == null) {
                res.setResultNote("区域不存在");
                return res;
            }
            Area city = areaService.get(area.getParentId());
            Area province = null;
            if (city != null) {
                province = areaService.get(city.getParentId());
            }
            String province1 = province != null ? province.getName() : "";
            String city1 =city != null ? city.getName() : "";
            String district1 =area.getName();
                // 调用三方接口
                List<WohuiEntity> list = Lists.newArrayList();
                list.add(new WohuiEntity("Province", province1));
                list.add(new WohuiEntity("City", city1));
                list.add(new WohuiEntity("District", district1, false));
				list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
				list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
				JSONObject object = WohuiUtils.send(WohuiUtils.HP_UserList, list);
                JSONArray array = object.getJSONArray("data");
				BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//付款时的手续费
				int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
				res.setTotalPage(renewNum);
				res.put("rowsCount",object.getString("rowsCount"));
                if (!"0000".equals(object.getString("respCode"))) {
                    res.setResultNote("获取失败："+object.getString("respMsg"));
                } else {

					List<Map<String, Object>> dataList = Lists.newArrayList();
					if(array != null && !array.isEmpty()){
						res.setDataList(array);
					}else{
						res.setDataList(dataList);
					}
                    res.setResult("0");
                    res.setResultNote("获取成功");
                }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return res;
    }
	/**
	 * 2020/7/18新增
	 * 会员提现银行卡-列表接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForUserBankList")
	@ResponseBody
	public ResJson ForUserBankList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
				// 调用三方接口
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("CardGUID", req.getString("uid")));
				JSONObject object = WohuiUtils.send(WohuiUtils.UserBankList, list);
				JSONArray array = object.getJSONArray("data");
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("获取失败："+object.getString("respMsg"));
				} else {
					res.put("rowsCount",object.getString("rowsCount"));
					List<Map<String, String>> dataList = Lists.newArrayList();
					if(array != null && !array.isEmpty()){
                        for (int i = 0; i < array.size(); i++) {
                            JSONObject data = array.getJSONObject(i);
                            Map<String, String> map = Maps.newHashMap();
                            map.put("UB_GUID", data.getString("UB_GUID"));
                            map.put("UB_CardGUID", data.getString("UB_CardGUID"));
                            map.put("UB_BankCode", data.getString("UB_BankCode"));
                            map.put("UB_BankName", data.getString("UB_BankName"));
                            map.put("UB_UserName", data.getString("UB_UserName"));
                            map.put("UB_Number", data.getString("UB_Number"));
                            map.put("Number", "****   ****   ****   "+data.getString("UB_Number").substring(data.getString("UB_Number").length() - 4));
                            dataList.add(map);
                        }
                        res.setDataList(dataList);
					}else{
						res.setDataList(dataList);
					}
					res.setResult("0");
					res.setResultNote("获取成功");
				}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 2020/7/18新增
	 * 会员提现银行卡-添加 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForUserBankAdd")
	@ResponseBody
	public ResJson ForUserBankAdd(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
//			if (StringUtils.isBlank(req.getString("bankcode"))) {
//				res.setResultNote("12位联行号不能为空！");
//				return res;
//			}
			if (StringUtils.isBlank(req.getString("bankname"))) {
				res.setResultNote("银行名称不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("address"))) {
				res.setResultNote("开户行地址不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("username"))) {
				res.setResultNote("银行卡户名不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("banknumber"))) {
				res.setResultNote("16或19位银行卡号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("BankCode", ""));
			list.add(new WohuiEntity("BankName", req.getString("bankname")));
			list.add(new WohuiEntity("Address", req.getString("address")));
			list.add(new WohuiEntity("UserName", req.getString("username")));
			list.add(new WohuiEntity("BankNumber", req.getString("banknumber")));
			JSONObject object = WohuiUtils.send(WohuiUtils.UserBankAdd, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setDataList(array);
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 2020/7/18新增
	 * 会员提现银行卡-删除 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForUserBankDelete")
	@ResponseBody
	public ResJson ForUserBankDelete(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("bankguid"))) {
				res.setResultNote("银行卡号GUID不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("BankGUID", req.getString("bankguid")));
			JSONObject object = WohuiUtils.send(WohuiUtils.UserBankDelete, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setDataList(array);
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 2020/7/18新增
	 * 会员提现  接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForWithdrawalsAdd")
	@ResponseBody
	public ResJson ForWithdrawalsAdd(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("bankguid"))) {
				res.setResultNote("银行卡guid不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("money"))) {
				res.setResultNote("提现金额不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("Money", req.getString("money")));
			list.add(new WohuiEntity("BankGUID", req.getString("bankguid")));
			JSONObject object = WohuiUtils.send(WohuiUtils.WithdrawalsAdd, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setDataList(array);
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 注册会员列表接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForRegCardList")
	@ResponseBody
	public ResJson ForRegCardList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			list.add(new WohuiEntity("Number", StringUtils.isNotEmpty(req.getString("number"))?req.getString("number"):""));
			list.add(new WohuiEntity("RealName", StringUtils.isNotEmpty(req.getString("realname"))?req.getString("realname"):""));
			list.add(new WohuiEntity("Phone", StringUtils.isNotEmpty(req.getString("phone"))?req.getString("phone"):""));
			JSONObject object = WohuiUtils.send(WohuiUtils.RegCardList, list);
			JSONArray array = object.getJSONArray("data");
			BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//付款时的手续费
			int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
			res.setTotalPage(renewNum);
			res.put("rowsCount",object.getString("rowsCount"));
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {

				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 会员收入列表接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCardIncomeList")
	@ResponseBody
	public ResJson ForCardIncomeList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			list.add(new WohuiEntity("OrderNO", StringUtils.isNotEmpty(req.getString("orderno"))?req.getString("orderno"):""));
			list.add(new WohuiEntity("DateBegin", StringUtils.isNotEmpty(req.getString("datebegin"))?req.getString("datebegin"):""));
			list.add(new WohuiEntity("DateEnd", StringUtils.isNotEmpty(req.getString("dateend"))?req.getString("dateend"):""));
			list.add(new WohuiEntity("Remark", StringUtils.isNotEmpty(req.getString("remark"))?req.getString("remark"):""));
			JSONObject object = WohuiUtils.send(WohuiUtils.CardIncomeList, list);
			JSONArray array = object.getJSONArray("data");
			BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//付款时的手续费
			int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
			res.setTotalPage(renewNum);
			res.put("rowsCount",object.getString("rowsCount"));
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {

				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	/**
	 * 云店铺代理产品更换接口wind
	 * @param req
	 * @return
	 */
	@PostMapping("/ForMSMGoodsChange")
	@ResponseBody
	public ResJson ForMSMGoodsChange(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("goodsid"))) {
				res.setResultNote("商品ID不能为空！");
				return res;
			}
			String goodssign =" ";
			if("PDD".equals(req.getString("source"))){
				if (!StringUtils.isBlank(req.getString("goodssign"))) {
					goodssign=req.getString("goodssign");
				}
			}
		if (!isBlank(req.getString("msmgguid"), req.getString("source"), req.getString("goodsname"), req.getString("imgurl"))) {
		// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("MSMGGUID", req.getString("msmgguid")));
			list.add(new WohuiEntity("Source", req.getString("source")));
			list.add(new WohuiEntity("GoodsID", req.getString("goodsid")));
			list.add(new WohuiEntity("GoodsSign", goodssign));
			list.add(new WohuiEntity("GoodsName", req.getString("goodsname"), false));
			list.add(new WohuiEntity("ImgUrl", req.getString("imgurl"), false));
			JSONObject object = WohuiUtils.send(WohuiUtils.MSMGoodsChange, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setDataList(array);
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增4/11
	 *会员流量补贴申请接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForLLBTApply")
	@ResponseBody
	public ResJson ForLLBTApply(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
//			res.setResultNote("请更新APP到最新版本！");
		if (StringUtils.isBlank(req.getString("uid"))) {
			res.setResultNote("用户账号不能为空！");
			return res;
		}
		Llbt llbt = new Llbt();
		llbt.setMember(new Member(req.getString("uid")));
		List<Llbt> opList = llbtMapper.findList(llbt);
		if (opList != null && opList.size() > 0) {
			for (Llbt llbt2 : opList) {
				Map<String, Object> map1 = new HashMap<String, Object>();
				if ("0".equals(llbt2.getState())) {
					llbtService.executeUpdateSql("UPDATE t_llbtapply SET state = '2' WHERE id = '" + llbt2.getId() + "' AND state = '0'");
					List<WohuiEntity> list = Lists.newArrayList();
					list.add(new WohuiEntity("OrderNO", llbt2.getOrderNo()));
					JSONObject object = WohuiUtils.send(WohuiUtils.LLBTCancel, list);
					JSONArray array = object.getJSONArray("data");
					if (!"0000".equals(object.getString("respCode"))) {
						res.setResultNote("订单取消失败："+object.getString("respMsg"));
						return res;
					}
				}else if("1".equals(llbt2.getState())){
					res.setResultNote("该用户已申请过流量补贴");
					return res;
				}
			}
		}
		int goodsnum = 0;//商品数量GetUInfoByGUID
		List<WohuiEntity> data = Lists.newArrayList();
		data.add(new WohuiEntity("UGUID", req.getString("uid")));
		JSONObject unifor = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, data);
		if (!"0000".equals(unifor.getString("respCode"))) {
			res.setResultNote("获取失败："+unifor.getString("respMsg"));
			return res;
		}
		JSONArray data2 = unifor.getJSONArray("data");
		if (data2 != null && !data2.isEmpty()) {
			JSONObject object2 = data2.getJSONObject(0);
			int C_GoodsSum= Integer.parseInt(object2.getString("C_GoodsSum"));
			goodsnum = 50-C_GoodsSum;
		}else{
			res.setResultNote("获取失败：流量补贴商品数据获取失败");
			return res;
		}
		int money = 0;//支付金额
			money = goodsnum*3;
        if(money<=0){
            res.setResultNote("该用户不可申请流量补贴");
            return res;
        }
		String orderId ="LLBT" + IdGen.getOrderNo();//流量补贴单号
		Llbt o = new Llbt();
		o.setOrderNo(orderId);
		o.setGoodsnum(String.valueOf(goodsnum));
		o.setCreatedate(new Date());
		o.setMoney(String.valueOf(money));
		o.setMember(new Member(req.getString("uid")));
		o.setState("0");
		llbtService.save(o);
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("OrderNO", orderId));
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("GoodsNum", String.valueOf(goodsnum)));
			list.add(new WohuiEntity("Money", String.valueOf(money)));
			JSONObject object = WohuiUtils.send(WohuiUtils.LLBTApply, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
                return res;
			}else{
				res.setResult("0");
				res.setResultNote("获取成功");
			}
			res.put("goodsnum",goodsnum);
			res.put("money",money);
			res.put("orderno",orderId);
			res.setDataList(array);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增4/11
	 *会员流量补贴取消申请接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForLLBTCancel")
	@ResponseBody
	public ResJson ForLLBTCancel(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
		if (StringUtils.isBlank(req.getString("orderno"))) {
			res.setResultNote("订单号不能为空！");
			return res;
		}
			Llbt llbt = llbtService.getOrderno(req.getString("orderno"));
			res.setResult("0");
			res.setResultNote("获取成功");
			llbt.setState("2");
			llbt.setCanceldate(new Date());
			llbtService.save(llbt);
//		llbtService.executeUpdateSql("UPDATE t_llbt SET state = '2' WHERE orderno = '"+req.getString("orderno"));
		// 调用三方接口
		List<WohuiEntity> list = Lists.newArrayList();
		list.add(new WohuiEntity("OrderNO", req.getString("orderno")));
		JSONObject object = WohuiUtils.send(WohuiUtils.LLBTCancel, list);
		JSONArray array = object.getJSONArray("data");
		if (!"0000".equals(object.getString("respCode"))) {
			res.setResultNote("获取失败："+object.getString("respMsg"));
		} else {
			res.setResult("0");
			res.setResultNote("获取成功");
		}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增4/11
	 *会员流量补贴支付接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForLLBTPay")
	@ResponseBody
	public ResJson ForLLBTPay(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
		if (StringUtils.isBlank(req.getString("orderno"))) {
			res.setResultNote("订单号不能为空！");
			return res;
		}
			Llbt llbt = llbtService.getOrderno(req.getString("orderno"));
			llbt.setState("1");
			llbt.setPayDate(new Date());
			llbt.setFinishdate(new Date());
			llbtService.save(llbt);
//		llbtService.executeUpdateSql("UPDATE t_llbt SET state = '1' WHERE orderno = '"+req.getString("orderno")+"' AND state = '0'");
		// 调用三方接口
		List<WohuiEntity> list = Lists.newArrayList();
		list.add(new WohuiEntity("OrderNO", req.getString("orderno")));
		JSONObject object = WohuiUtils.send(WohuiUtils.LLBTPay, list);
		JSONArray array = object.getJSONArray("data");
		if (!"0000".equals(object.getString("respCode"))) {
			res.setResultNote("获取失败："+object.getString("respMsg"));
		} else {
			res.setResult("0");
			res.setResultNote("获取成功");
		}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增4/11
	 *设置联系信息接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForSetContact")
	@ResponseBody
	public ResJson ForSetContact(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
		if (!isBlank(req.getString("uid"), req.getString("wechat"), req.getString("usephone"))) {
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("WeChat", req.getString("wechat")));
			list.add(new WohuiEntity("UsePhone", req.getString("usephone")));
			JSONObject object = WohuiUtils.send(WohuiUtils.SetContact, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setDataList(array);
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增9/12
	 *判断是否第一次下单
	 * @param req
	 * @return
	 */
	@PostMapping("/IsfirstXHQApply")
	@ResponseBody
	public ResJson IsfirstXHQApply(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户账号不能为空！");
				return res;
			}
            String type = "1";//状态1第一次 ,2第二次
            List<Map<String, Object>> list = xhqService.executeSelectSql("SELECT state,id FROM t_xhqapply WHERE state=1 and uid = '" + req.getString("uid") + "' limit 1 ");
            if (list != null && !list.isEmpty()) {
				type = "2";
            }
			res.put("type",type);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增9/11
	 *选获权申请接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForXHQApply")
	@ResponseBody
	public ResJson ForXHQApply(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (!isBlank(req.getString("uid"), req.getString("Num"))) {

				Xhq xhq = new Xhq();
				xhq.setMember(new Member(req.getString("uid")));
				List<Xhq> opList = xhqService.findList(xhq);
				if (opList != null && opList.size() > 0) {
					for (Xhq xhq2 : opList) {
						Map<String, Object> map1 = new HashMap<String, Object>();
						if ("0".equals(xhq2.getState())) {
							xhqService.executeUpdateSql("UPDATE t_xhqapply SET state = '2' WHERE id = '" + xhq2.getId() + "' AND state = '0'");
							List<WohuiEntity> list = Lists.newArrayList();
							list.add(new WohuiEntity("OrderNO", xhq2.getId()));
							JSONObject object = WohuiUtils.send(WohuiUtils.XHQCancel, list);
							JSONArray array = object.getJSONArray("data");
							if (!"0000".equals(object.getString("respCode"))) {
								res.setResultNote("选货权订单取消失败："+object.getString("respMsg")+"单号："+xhq2.getId());
							}
						}
					}
				}
				String orderId ="XHQ" + IdGen.getOrderNo();//选货权单号
				Xhq o = new Xhq();
				o.setId(orderId);
				o.setGoodsnum(req.getString("Num"));
				o.setCreatedate(new Date());
				int Money = Integer.parseInt(req.getString("Num"))*3;
				o.setMoney(String.valueOf(Money));
				o.setMember(new Member(req.getString("uid")));
				o.setState("0");
				xhqMapper.insert(o);
				// 调用三方接口
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("OrderNO", o.getId()));
				list.add(new WohuiEntity("CardGUID", req.getString("uid")));
				list.add(new WohuiEntity("Num", o.getGoodsnum()));
				JSONObject object = WohuiUtils.send(WohuiUtils.XHQApply, list);
				JSONArray array = object.getJSONArray("data");
				res.put("goodsnum",o.getGoodsnum());
				res.put("money",o.getMoney());
				res.put("orderno",o.getId());
				res.setDataList(array);
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("获取失败："+object.getString("respMsg"));
				} else {
					res.setResult("0");
					res.setResultNote("获取成功");
				}
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 产品周转中心可申请列表
	 * @param req
	 * @return
	 */
	@PostMapping("/FindPTCLists")
	@ResponseBody
	public ResJson FindPTCLists(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			// 商品列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Ptc ptc = new Ptc();
			ptc.setMember(new Member(req.getUid()));
			ptc.setState("0");
			Page<Ptc> page = ptcService.findPage(new Page<Ptc>(req.getPageNo(), req.getPageSize()),
					ptc);
			for (Ptc n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("orderno", n.getOrderNo());
				map.put("title", n.getTitle());
				map.put("type", n.getType());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增2021 1/2
	 *产品周转中心-开通 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPTCOpen")
	@ResponseBody
	public ResJson ForPTCOpen(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("province"))) {
				res.setResultNote("负责省份不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("负责城市不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("role"))) {
				res.setResultNote("开通身份不能为空！");
				return res;
			}
				String orderid = "";//状态不可申请 ,1可以申请
				String orderno = "";//商品订单号
			List<Map<String,Object>> list2 = ptcService.executeSelectSql("SELECT uid,type,id,orderno FROM t_ptcapply WHERE uid='"+req.getString("uid")+"' AND type='"+req.getString("role")+"' AND state<'1' ");
			if (list2 != null && !list2.isEmpty()) {
				Map<String, Object> map = list2.get(0);
				orderid = map.get("id").toString();
				orderno = map.get("orderno").toString();
			}else{
				res.setResultNote("您还不能开通产品周转中心权益！");
				return res;
			}
			Ptc ptc = ptcMapper.get(orderid);
			if (ptc != null && "0".equals(ptc.getState())) {
				ptc.setProvince(req.getString("province"));
				ptc.setCity(req.getString("city"));
				ptc.setArea(req.getString("district"));
				ptc.setState("1");
				ptc.setPayDate(new Date());
				ptc.setFinishdate(new Date());
				ptcMapper.update(ptc);
			}else{
				res.setResultNote("您还不能申请产品周转中心权益！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("Province", req.getString("province")));
			list.add(new WohuiEntity("City", req.getString("city")));
			list.add(new WohuiEntity("District",req.getString("district"),false));
			list.add(new WohuiEntity("Money",ptc.getMoney()));
			list.add(new WohuiEntity("OrderNO", orderno));
			list.add(new WohuiEntity("Role", req.getString("role")));
			JSONObject object = WohuiUtils.send(WohuiUtils.PTCOpen, list);
			JSONArray array = object.getJSONArray("data");
			res.put("goodsnum",ptc.getGoodsnum());
			res.put("money",ptc.getMoney());
			res.put("orderno",ptc.getId());
			res.setDataList(array);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
				ptc.setState("0");
				ptcMapper.update(ptc);
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 惠康区域代理-可申请列表
	 * @param req
	 * @return
	 */
	@PostMapping("/FindHKQYALists")
	@ResponseBody
	public ResJson FindHKQYALists(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败");
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			// 商品列表
			List<Map<String, Object>> dataList = Lists.newArrayList();
			Hkqy o = new Hkqy();
			o.setMember(new Member(req.getUid()));
			o.setState("0");
			Page<Hkqy> page = hkqyService.findPage(new Page<Hkqy>(req.getPageNo(), req.getPageSize()),
					o);
			for (Hkqy n : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("orderno", n.getOrderNo());
				map.put("title", n.getTitle());
				map.put("type", n.getType());
				map.put("tztype", n.getTztype());
				dataList.add(map);
			}
			res.setTotalPage(page.getTotalPage());
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增2022 3/18
	 *惠康区域代理-开通 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForHKQYAOpen")
	@ResponseBody
	public ResJson ForHKQYAOpen(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("province"))) {
				res.setResultNote("负责省份不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("负责城市不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("role"))) {
				res.setResultNote("开通身份不能为空！");
				return res;
			}
			String orderid = "";//状态不可申请 ,1可以申请
			String orderno = "";//商品订单号
			String type = "";//类型(体验 10,正式 20)
			List<Map<String,Object>> list2 = hkqyService.executeSelectSql("SELECT uid,type,id,orderno,tz_type FROM t_hkqyapply WHERE uid='"+req.getString("uid")+"' AND type='"+req.getString("role")+"' AND state<'1' ");
			if (list2 != null && !list2.isEmpty()) {
				Map<String, Object> map = list2.get(0);
				orderid = map.get("id").toString();
				orderno = map.get("orderno").toString();
				type = map.get("tz_type").toString();
			}else{
				res.setResultNote("您还不能开通惠康区域代理权益！");
				return res;
			}
			Hkqy o = hkqyMapper.get(orderid);
			if (o != null && "0".equals(o.getState())) {
				o.setProvince(req.getString("province"));
				o.setCity(req.getString("city"));
				o.setArea(req.getString("district"));
				o.setState("1");
				o.setPayDate(new Date());
				o.setFinishdate(new Date());
				hkqyMapper.update(o);
			}else{
				res.setResultNote("您还不能申请惠康区域代理权益！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("Province", req.getString("province")));
			list.add(new WohuiEntity("City", req.getString("city")));
			list.add(new WohuiEntity("District",req.getString("district"),false));
			list.add(new WohuiEntity("OrderNO", orderno));
			list.add(new WohuiEntity("Role", req.getString("role")));
			list.add(new WohuiEntity("Type", type));
			JSONObject object = WohuiUtils.send(WohuiUtils.HKQYAOpen, list);
			JSONArray array = object.getJSONArray("data");
			res.put("goodsnum",o.getGoodsnum());
			res.put("money",o.getMoney());
			res.put("orderno",o.getId());
			res.setDataList(array);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
				o.setState("0");
				hkqyMapper.update(o);
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增2021 4/12
	 *平台代理-开通 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPTAOpen")
	@ResponseBody
	public ResJson ForPTAOpen(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("province"))) {
				res.setResultNote("负责省份不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("负责城市不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("Province", req.getString("province")));
			list.add(new WohuiEntity("City", req.getString("city")));
			list.add(new WohuiEntity("District",req.getString("district"),false));
			JSONObject object = WohuiUtils.send(WohuiUtils.PTAOpen, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增2021 3/22
	 *版块代理-开通 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForBKAOpen")
	@ResponseBody
	public ResJson ForBKAOpen(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("province"))) {
				res.setResultNote("负责省份不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("负责城市不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("bkcode"))) {
				res.setResultNote("版块编码不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("Province", req.getString("province")));
			list.add(new WohuiEntity("City", req.getString("city")));
			list.add(new WohuiEntity("District",req.getString("district"),false));
			list.add(new WohuiEntity("BKCode",req.getString("bkcode")));
			JSONObject object = WohuiUtils.send(WohuiUtils.BKAOpen, list);
			JSONArray array = object.getJSONArray("data");
			res.setDataList(array);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增2021 3/22
	 *版块代理-开通 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForBKAOpen2")
	@ResponseBody
	public ResJson ForBKAOpen2(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("province"))) {
				res.setResultNote("负责省份不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("负责城市不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("bkcode"))) {
				res.setResultNote("版块编码不能为空！");
				return res;
			}
			String orderid = "";//状态不可申请 ,1可以申请
			String num = "1";//数量
			List<Map<String,Object>> list3 = kydService.executeSelectSql("SELECT * FROM t_kydapply WHERE uid='"+req.getString("uid")+"'and state=0 ORDER BY create_date DESC");
			if (list3 == null || list3.isEmpty()) {
				res.setResultNote("该账户未达到申请的条件！");
				return res;
			}
			Kyd o = new Kyd();
			Map<String, Object> map1 = list3.get(0);
			orderid = map1.get("orderno").toString();
			o.setId(map1.get("id").toString());
			o.setOrderNo(orderid);
			o.setMoney(map1.get("money").toString());
			o.setCreateDate(new Date());
			o.setPayDate(new  Date());
			o.setProvince(req.getString("province"));
			o.setCity(req.getString("city"));
			o.setArea(req.getString("district"));
			o.setMember(new Member(req.getString("uid")));
			o.setState("1");
			kydMapper.update(o);
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("OrderNO", orderid));
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("Province", req.getString("province")));
			list.add(new WohuiEntity("City", req.getString("city")));
			list.add(new WohuiEntity("District",req.getString("district"),false));
			list.add(new WohuiEntity("BKCode",req.getString("bkcode")));
			JSONObject object = WohuiUtils.send(WohuiUtils.BKAOpen, list);
			JSONArray array = object.getJSONArray("data");
			res.put("orderno",orderid);
			res.setDataList(array);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
				o.setState("0");
				kydMapper.update(o);
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增10/23
	 *赠品支付申请接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForGiftApply")
	@ResponseBody
	public ResJson ForGiftApply(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("gguid"))) {
				res.setResultNote("赠品编号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("money"))) {
				res.setResultNote("综合服务费金额不能为空！");
				return res;
			}

			Gift gift = new Gift();
			gift.setGguid(req.getString("gguid"));
			gift = giftService.findUniqueByProperty("gguid",
					req.getString("gguid"));
			if (gift != null) {
				BigDecimal money = new BigDecimal(req.getString("money"));
				res.put("goodsnum","1");
				res.put("money",gift.getMoney());
				res.put("orderno",gift.getId());
				res.setResult("0");
				res.setResultNote("获取成功");
				return res;
			}
			String orderId ="GIFT" + IdGen.getOrderNo();//赠品支付单号
			Gift o = new Gift();
			o.setId(orderId);
			o.setGoodsnum("1");
			o.setGguid(req.getString("gguid"));
			o.setCreatedate(new Date());
			o.setMoney(req.getString("money"));
			o.setMember(new Member(req.getString("uid")));
			o.setState("0");
			giftMapper.insert(o);
			res.put("goodsnum",o.getGoodsnum());
			res.put("money",o.getMoney());
			res.put("orderno",o.getId());
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 新增9/11
	 *选货权支付接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForXHQPay")
	@ResponseBody
	public ResJson ForXHQPay(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (!isBlank(req.getString("OrderNO"))) {
				// 调用三方接口
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("OrderNO", req.getString("OrderNO")));
				JSONObject object = WohuiUtils.send(WohuiUtils.XHQPay, list);
				JSONArray array = object.getJSONArray("data");
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("获取失败："+object.getString("respMsg"));
				} else {
					res.setResult("0");
					res.setResultNote("获取成功");
				}
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增9/11
	 *选获权取消申请接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForXHQCancel")
	@ResponseBody
	public ResJson ForXHQCancel(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (!isBlank(req.getString("OrderNO"))) {
				// 调用三方接口
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("OrderNO", req.getString("OrderNO")));
				JSONObject object = WohuiUtils.send(WohuiUtils.XHQCancel, list);
				JSONArray array = object.getJSONArray("data");
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("获取失败："+object.getString("respMsg"));
				} else {
					res.setResult("0");
					res.setResultNote("获取成功");
				}
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增9/11
	 *选获权转让接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForXHQTurn")
	@ResponseBody
	public ResJson ForXHQTurn(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (!isBlank(req.getString("OutGUID"), req.getString("phone"), req.getString("Num"))) {

				List<WohuiEntity> entityList = Lists.newArrayList();
				entityList.add(new WohuiEntity("Phone", req.getString("phone")));
				JSONObject object2 = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, entityList);
				if (!"0000".equals(object2.getString("respCode"))) {
					res.setResultNote("被授权的我惠账号不存在！");
					return res;
				}
				JSONArray array2 = object2.getJSONArray("data");
				JSONObject data2 = array2.getJSONObject(0);
				String InGUID = data2.getString("C_GUID");
				if(req.getString("OutGUID").equals(InGUID)){
					res.setResultNote("授权和被授权的我惠账号不能相同！");
					return res;
				}
				// 调用三方接口
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("OutGUID", req.getString("OutGUID")));
				list.add(new WohuiEntity("InGUID", InGUID));
				list.add(new WohuiEntity("Num", req.getString("Num")));
				list.add(new WohuiEntity("Remark", req.getString("Remark")));
				JSONObject object = WohuiUtils.send(WohuiUtils.XHQTurn, list);
				JSONArray array = object.getJSONArray("data");
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("获取失败："+object.getString("respMsg"));
				} else {
					res.setResult("0");
					res.setResultNote("获取成功");
				}
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 选获权转让列表
	 * @param req
	 * @return
	 */
	@PostMapping("/ForXHQTurnList")
	@ResponseBody
	public ResJson ForXHQTurnList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			JSONObject object = WohuiUtils.send(WohuiUtils.XHQTurnList, list);
			JSONArray array = object.getJSONArray("data");
			BigDecimal num = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//
			int renewNum  = (int) num.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
			res.setTotalPage(renewNum);
			res.put("rowsCount",object.getString("rowsCount"));
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {

				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增7/31
	 *单品代理转让接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPCANumTurn")
	@ResponseBody
	public ResJson ForPCANumTurn(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (!isBlank(req.getString("OutGUID"), req.getString("phone"), req.getString("Num"))) {

				List<WohuiEntity> entityList = Lists.newArrayList();
				entityList.add(new WohuiEntity("Phone", req.getString("phone")));
				JSONObject object2 = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, entityList);
				if (!"0000".equals(object2.getString("respCode"))) {
					res.setResultNote("被授权的我惠账号不存在！");
					return res;
				}
				JSONArray array2 = object2.getJSONArray("data");
				JSONObject data2 = array2.getJSONObject(0);
				String InGUID = data2.getString("C_GUID");
				if(req.getString("OutGUID").equals(InGUID)){
					res.setResultNote("授权和被授权的我惠账号不能相同！");
					return res;
				}
				// 调用三方接口
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("OutGUID", req.getString("OutGUID")));
				list.add(new WohuiEntity("InGUID", InGUID));
				list.add(new WohuiEntity("Num", req.getString("Num")));
				JSONObject object = WohuiUtils.send(WohuiUtils.PCANumTurn, list);
				JSONArray array = object.getJSONArray("data");
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("获取失败："+object.getString("respMsg"));
				} else {
					res.setResult("0");
					res.setResultNote("获取成功");
				}
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 大健康签到列表
	 * @param req
	 * @return
	 */
	@PostMapping("/ForBHSignList")
	@ResponseBody
	public ResJson ForBHSignList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			JSONObject object = WohuiUtils.send(WohuiUtils.BHSignList, list);
			JSONArray array = object.getJSONArray("data");
			BigDecimal num = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//
			int renewNum  = (int) num.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
			res.setTotalPage(renewNum);
			res.put("rowsCount",object.getString("rowsCount"));
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {

				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增7/30
	 *大健康签收接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForBHSignAdd")
	@ResponseBody
	public ResJson ForBHSignAdd(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			JSONObject object = WohuiUtils.send(WohuiUtils.BHSignAdd, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				if(array != null && !array.isEmpty()){
					JSONObject obj = array.getJSONObject(0);
					res.put("respCode",obj.getString("respCode"));
					res.put("respIsPrize",obj.getString("respIsPrize"));
					res.put("respPrizeMsg",obj.getString("respPrizeMsg"));
				}

				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增7/30
	 *是否已签到
	 * @param req
	 * @return
	 */
	@PostMapping("/ForBHIsSigned")
	@ResponseBody
	public ResJson ForBHIsSigned(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			JSONObject object = WohuiUtils.send(WohuiUtils.BHIsSigned, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 赠品列表
	 * @param req
	 * @return
	 */
	@PostMapping("/ForGiftList")
	@ResponseBody
	public ResJson ForGiftList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			JSONObject object = WohuiUtils.send(WohuiUtils.GiftList, list);
			JSONArray array = object.getJSONArray("data");
			BigDecimal num = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//
			int renewNum  = (int) num.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
			res.setTotalPage(renewNum);
			res.put("rowsCount",object.getString("rowsCount"));
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {

				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 新增9/20
	 *赠品签收接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForGiftSureSign")
	@ResponseBody
	public ResJson ForGiftSureSign(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("GiftGUID"))) {
				res.setResultNote("赠品编号不能为空");
				return res;
			}
				// 调用三方接口
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("GiftGUID", req.getString("GiftGUID")));
				JSONObject object = WohuiUtils.send(WohuiUtils.GiftSureSign, list);
				JSONArray array = object.getJSONArray("data");
				if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote("获取失败："+object.getString("respMsg"));
				} else {
					res.setResult("0");
					res.setResultNote("获取成功");
				}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增9/20
	 *赠品领取接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForGiftGoGet")
	@ResponseBody
	public ResJson ForGiftGoGet(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			String Remark ="";
			if (isBlank(req.getString("GiftGUID"))) {
				res.setResultNote("赠品编号不能为空");
				return res;
			}
			if (isBlank(req.getString("RealName"))) {
				res.setResultNote("收货人姓名不能为空");
				return res;
			}
			if (isBlank(req.getString("Phone"))) {
				res.setResultNote("收货人手机号不能为空");
				return res;
			}
			if (isBlank(req.getString("Province"))) {
				res.setResultNote("省份不能为空");
				return res;
			}
			if (isBlank(req.getString("City"))) {
				res.setResultNote("城市不能为空");
				return res;
			}
			if (!isBlank(req.getString("Remark"))) {
				Remark =req.getString("Remark");
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("GiftGUID", req.getString("GiftGUID")));
			list.add(new WohuiEntity("RealName", req.getString("RealName")));
			list.add(new WohuiEntity("Phone", req.getString("Phone")));
			list.add(new WohuiEntity("Province", req.getString("Province")));
			list.add(new WohuiEntity("City", req.getString("City")));
			list.add(new WohuiEntity("District", req.getString("District"), false));
			list.add(new WohuiEntity("Address", req.getString("Address"), false));
			list.add(new WohuiEntity("Remark", Remark, false));
			JSONObject object = WohuiUtils.send(WohuiUtils.GiftGoGet, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	/**
     * 新增获取txt文件下载量以及修改wind
     *num 参数0是不增加
     * @param req
     * @return
     */
    @PostMapping("/getputDownload")
    @ResponseBody
    public ResJson getputDownload(@RequestBody ReqJson req) {
        ResJson res = new ResJson();
        res.setResultNote("获取失败");
        try {
			String filePath = "D:\\java\\xzl.txt";
			File file=new File(filePath);
			int s = 0;
			if(file.isFile() && file.exists()){ //判断文件是否存在
				BufferedReader in = new BufferedReader(new FileReader(filePath));
				if(!"0".equals(req.getString("num"))){
					s =  Integer.parseInt(in.readLine())+1;
				}else{
					s =  Integer.parseInt(in.readLine());
				}
				BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
				out.write(Integer.toString(s));
				out.flush();
				out.close();
			}
			res.put("down",s);
            res.setResult("0");
            res.setResultNote("获取成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return res;
    }
	/**
	 * 根据guid查询自己购买过的商品
	 * @param req
	 * @return
	 */
	@PostMapping("/ForGetzjgooods")
	@ResponseBody
	public ResJson ForGetzjgooods(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			List<Map<String, Object>> dataList = Lists.newArrayList();
			if (!isBlank(req.getUid())) {
					List<Map<String,Object>> list = productOrderService.executeSelectSql("SELECT i.product_id AS goodid ,i.product_title AS title,i.product_icon AS icon,a.state AS state,'3' AS type FROM t_product_order a LEFT JOIN t_order_item i on i.order_id=a.id WHERE a.uid='"+req.getUid()+"' AND a.state<5 AND a.state>0 " +
							"UNION ALL  SELECT item_id AS goodid ,item_title AS title, item_img AS icon,tk_status AS state,type AS type FROM t_taoke_order WHERE uid='"+req.getUid()+"' AND tk_status<>'13' AND tk_status<>'-1' AND tk_status<>'10'");
					if (list != null && !list.isEmpty()) {
						for (Map<String, Object> map : list) {
							Map<String, Object> map2 = Maps.newHashMap();
							map2.put("goodid", map.get("goodid").toString());
							map2.put("title", map.get("title").toString());
							map2.put("icon",getRealImage(map.get("icon").toString()));
							map2.put("type",map.get("type").toString());
							map2.put("state",map.get("state").toString());
							dataList.add(map2);
						}
					}
					res.setDataList(dataList);
					res.setResult("0");
					res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 根据商户ID查询下过的订单
	 * @param req
	 * @return
	 */
	@PostMapping("/ForGetShoporder")
	@ResponseBody
	public ResJson ForGetShoporder(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			ShopbusOrder shopbusorder= new ShopbusOrder();
			shopbusorder.setShop(shop);
//			if (!StringUtils.isBlank(req.getString("state"))) {//
//				shopbusorder.setState(req.getString("state"));
//			}
//
			shopbusorder.setState("3");
			Page<ShopbusOrder> page = shopbusorderService.findPage(new Page<>(req.getPageNo(), req.getPageSize()), shopbusorder);
			res.setTotalPage(page.getTotalPage());
			List<Map<String, String>> shopbusorderList = Lists.newArrayList();
			for (ShopbusOrder b : page.getList()) {
				//参团会员
				Map<String, String> map = Maps.newHashMap();
				Member member=b.getMember();
				map.put("phone", member.getPhone());
				map.put("name", member.getNickname());

				map.put("Id", b.getId());
				map.put("price", b.getPrice());
				map.put("amount", b.getAmount());

				map.put("create_date",  b.getCreateDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(b.getCreateDate()) : "");
				map.put("pay_date",  b.getPayDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(b.getPayDate()) : "");
				map.put("state", String.valueOf(b.getState()));
				map.put("pay_type", String.valueOf(b.getPayType()));
				shopbusorderList.add(map);
			}
			res.put("orderList",shopbusorderList);
			res.setResult("0");
			res.setResultNote("获取成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 根据会员ID查询下过的商圈订单
	 * @param req
	 * @return
	 */
	@PostMapping("/ForGetMyShoporder")
	@ResponseBody
	public ResJson ForGetMyShoporder(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("会员ID不能为空");
				return res;
			}
			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			ShopbusOrder shopbusorder= new ShopbusOrder();
			shopbusorder.setMember(member);
			shopbusorder.setState("3");
			Page<ShopbusOrder> page = shopbusorderService.findPage(new Page<>(req.getPageNo(), req.getPageSize()), shopbusorder);
			res.setTotalPage(page.getTotalPage());
			List<Map<String, String>> shopbusorderList = Lists.newArrayList();
			for (ShopbusOrder b : page.getList()) {
				Map<String, String> map = Maps.newHashMap();
				member=b.getMember();
				map.put("phone", member.getPhone());
				map.put("name", member.getNickname());
				map.put("title", b.getShop().getTitle());
				map.put("images", b.getShop().getIcon());

				map.put("Id", b.getId());
				map.put("price", b.getPrice());
				map.put("amount", b.getAmount());
				map.put("point", new BigDecimal(0.4).multiply(new BigDecimal(b.getPtrefee())).setScale(4, BigDecimal.ROUND_DOWN).toString());
				map.put("hyrefee", b.getHyrefee());

				map.put("create_date", b.getCreateDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(b.getCreateDate()) : "");
				map.put("pay_date", b.getPayDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(b.getPayDate()) : "");
				map.put("state", String.valueOf(b.getState()));
				map.put("pay_type", String.valueOf(b.getPayType()));
				shopbusorderList.add(map);
			}
			res.setDataList(shopbusorderList);
			res.setResult("0");
			res.setResultNote("获取成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新实体店铺信息（线下订单）
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/shopInfoOrder")
	@ResponseBody
	public ResJson shopInfoOrder(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("查询失败！");
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空！");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该商家不存在！");
				return res;
			}
			// 今日销售额
			String daySales = "0";
			String dayCollection = "0";//收款金额
			String daySalesVolume = "0";
			List<Map<String,Object>> list = shopbusorderService.executeSelectSql("SELECT IFNULL(SUM(price),0) price,IFNULL(SUM(amount),0) amount,COUNT(id) count FROM t_shop_order WHERE shop_id = '"+shop.getId()+"' AND state = 3 AND DATE(create_date) = CURDATE()");
			if (list != null && !list.isEmpty()) {
				Map<String, Object> map = list.get(0);
				if (map.get("price") != null) {
					daySales = map.get("price").toString();
				}
				if (map.get("amount") != null) {
					dayCollection = map.get("amount").toString();
				}
				if (map.get("count") != null) {
					daySalesVolume = map.get("count").toString();
				}
			}
			res.put("daySales", daySales);
			res.put("dayCollection", dayCollection);
			res.put("daySalesVolume", daySalesVolume);
			String totalSales = "0";
			String totalCollection = "0";
			String totalSalesVolume = "0";
			List<Map<String,Object>> list1 = shopbusorderService.executeSelectSql("SELECT IFNULL(SUM(amount),0) amount,IFNULL(SUM(price),0) price,COUNT(id) count FROM t_shop_order WHERE shop_id = '"+shop.getId()+"' AND state = 3 " + (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime")) ? " AND create_date BETWEEN '"+req.getString("startTime")+"' AND '"+req.getString("endTime")+"'" : ""));
			if (list1 != null && !list1.isEmpty()) {
				Map<String, Object> map = list1.get(0);
				if (map.get("price") != null) {
					totalSales = map.get("price").toString();
				}
				if (map.get("amount") != null) {
					totalCollection = map.get("amount").toString();
				}
				if (map.get("count") != null) {
					totalSalesVolume = map.get("count").toString();
				}
			}
			res.put("totalSales", totalSales);
			res.put("totalCollection", totalCollection);
			res.put("totalSalesVolume", totalSalesVolume);

			// 累计客户
			String totalClient = shopbusorderService.executeGetSql("SELECT COUNT(DISTINCT a.uid) FROM t_shop_order a WHERE a.shop_id = '"+shop.getId()+"'" + (StringUtils.isNotBlank(req.getString("startTime")) && StringUtils.isNotBlank(req.getString("endTime")) ? " AND a.create_date BETWEEN '"+req.getString("startTime")+"' AND '"+req.getString("endTime")+"'" : "")).toString();
			res.put("totalClient", totalClient);

			res.setResult("0");
			res.setResultNote("查询成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 自己用测试接口
	 * @param req
	 * @return
	 */
	@PostMapping("/newbindceshi")
	@ResponseBody
	public ResJson newbindceshi(@RequestBody ReqJson req,HttpServletRequest request) {
		ResJson res = new ResJson();
		try {
			Map<String, String> params = Maps.newHashMap();
//			params.put("sid", MiaoyouquanUtils.sid);// 对应的淘客账号授权ID
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_activity, params);
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("status"))) {
				res.setResultNote(jsonObject.getString("content"));
				return res;
			}
			JSONArray jsonArray = jsonObject.getJSONArray("content");
			res.setDataList(jsonArray);
			res.setResult("0");
			res.setResultNote("查询成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 微信扫码获取openid
	 * @param req
	 * @return
	 */
	@PostMapping("/ForWxScanningCode")
	@ResponseBody
	public ResJson ForWxScanningCode(@RequestBody ReqJson req,HttpServletRequest request) {
		ResJson res = new ResJson();
		try {
			String openid="";
					String appid="wxfd00b75fa13f1b76";
					String AppSecret="44838dd42a856513397bd1322f0d7641";
					String code=req.getString("code");
					WxpubOAuth.OAuthResult OAuthResult=WxpubOAuth.getOpenId(appid,AppSecret,code);
					openid=(String)OAuthResult.getOpenid();
					if(StringUtils.isBlank(openid)){
						System.out.println(OAuthResult);
						res.setResultNote("code过期，请重新扫码！");
						return  res;
					}
					// 根据手机号查询用户信息
					res.put("openid",openid);
//					Member member = memberService.findUniqueByProperty("tx_openid", openid);
					Object uid = memberService.executeGetSql("SELECT id FROM t_member WHERE tx_openid = '" + openid + "' limit 1 ");
					if (uid == null ) {
						res.setResult("0");
						res.put("uid",uid);
						res.setResultNote("会员信息为空");
						return res;
					}
					res.put("uid",uid);
				res.setResult("0");
				res.setResultNote("操作成功");

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 支付宝扫码获取userid
	 * @param req
	 * @return
	 */
	@PostMapping("/ForALiScanningCode")
	@ResponseBody
	public ResJson ForALiScanningCode(@RequestBody ReqJson req,HttpServletRequest request) {
		ResJson res = new ResJson();
		try {
			String userId="";
			String nickName="";
			String avatar="";
					if (StringUtils.isBlank(req.getString("code"))) {
						res.setResultNote("支付宝授权码不能为空");
						return res;
					}
					Map<String, String> data = AlipayUtils.getAccessTokenAndUserId(req.getString("code"));
					for (String key : data.keySet()) {
						userId=data.get("userId");
						nickName=data.get("nickName");
						avatar=data.get("avatar");
					}
					res.putAll(data);
					// 根据手机号查询用户信息
//					Member member = memberService.findUniqueByProperty("aliid", userId);
					Object uid = memberService.executeGetSql("SELECT id FROM t_member WHERE aliid = '" + userId + "' limit 1 ");
					if (uid == null ) {
						res.setResult("0");
						res.put("uid",uid);
						res.setResultNote("会员信息为空");
						return res;
					}
					res.put("uid",uid);
				res.setResult("0");
				res.setResultNote("操作成功");

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 微信openid,支付宝ID绑定会员接口
	 * @param req
	 * @return
	 */
	@PostMapping("/BindMemberOpenid")
	@ResponseBody
	public ResJson BindMemberOpenid(@RequestBody ReqJson req,HttpServletRequest request) {
		ResJson res = new ResJson();
		try {
					// 根据手机号查询用户信息
					Member member = new Member();
//					if(!StringUtils.isBlank(req.getString("phone"))){
//						member = memberService.findUniqueByProperty("phone", req.getString("phone"));
//					}
					if(!StringUtils.isBlank(req.getString("uid"))){
						member = memberService.get(req.getString("uid"));
					}
					if (member == null ) {
						res.setResultNote("该用户不存在！");
						return res;
					}
					if("0".equals(req.getString("type"))){ //0是微信openid，1支付宝apliid
						if(StringUtils.isBlank(req.getString("opaliid"))){
							res.setResultNote("微信openid为空");
							return res;
						}
						member.setTxopenid(req.getString("opaliid"));
					}else if("1".equals(req.getString("type"))){
						if(StringUtils.isBlank(req.getString("opaliid"))){
							res.setResultNote("支付宝apliid为空");
							return res;
						}
						member.setAliid(req.getString("opaliid"));
					}
					memberService.save(member);
				res.setResult("0");
				res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 生成二微码图片
	 * @param req
	 * @return
	 */
	@PostMapping("/createQrCode")
	@ResponseBody
	public ResJson createQrCode(@RequestBody ReqJson req,HttpServletRequest request) {
		ResJson res = new ResJson();
		try {
			String qrcode;
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("该商家不存在！");
				return res;
			}
			if(StringUtils.isNotBlank(shop.getQrcode())){
				qrcode =shop.getQrcode();
			}else{
				//showType="QRPay"//app识别用的参数
//				String url="http://test.whyd365.com:8000/payNum?showType=QRPay&shopid="+req.getString("shopId");
				String url="https://m.whsq365.com/payNum?shopid="+req.getString("shopId")+"&showType=QRPay";

				String path="D:/userfiles/qrcode";
				String fileName=req.getString("shopId")+".png";
				String data=QrCodeUtil.createQrCode(url,path,fileName);
				qrcode ="/userfiles/qrcode/"+fileName;
				shop.setQrcode(qrcode);
				shopService.save(shop);
			}
			res.put("qrcode",getRealImage(qrcode));
			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 多多进宝多多客生成频道推广
	 * @param req
	 * @return
	 */
	@PostMapping("/DuoduoRouter")
	@ResponseBody
	public ResJson DuoduoRouter(@RequestBody ReqJson req,HttpServletRequest request) {
		ResJson res = new ResJson();
		try {
			String pid;
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			pid=member.getPddId();
			if(StringUtils.isBlank(member.getPddId())){
				//调用喵有券创建推广位接口给当前用户生成一个推广位id
				Map<String, String> params = Maps.newHashMap();
				params.put("pdname", MiaoyouquanUtils.pdname);
				params.put("number", "1");
				JSONObject jsonObject2 = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params);
				logger.debug("喵有券返回数据：" + jsonObject2.toString());
				if ("200".equals(jsonObject2.getString("code"))) {
					JSONObject dataObject=jsonObject2.getJSONObject("data");
					if(dataObject!=null){
						JSONArray pidList=dataObject.getJSONArray("p_id_list");
						if(pidList!=null && pidList.size()>0){
							member.setPddId(pidList.getJSONObject(0).getString("p_id"));
							memberService.save(member);
							pid=pidList.getJSONObject(0).getString("p_id");
						}
					}
				}
			}
			Map<String, String> params = Maps.newHashMap();
			params.put("pid", pid);
			params.put("resource_type", req.getString("resource_type"));
			params.put("generate_schema_url","true");
			params.put("generate_we_app","true");
//			params.put("url", URLEncoder.encode(req.getString("url","UTF-8")));
			if(!StringUtils.isBlank(req.getString("url"))){
				params.put("url",req.getString("url"));
			}
			JSONObject jsonObject = MiaoyouquanUtils.duoduorouterAPI(MiaoyouquanUtils.router,MiaoyouquanUtils.urlgen, params);
			if(!StringUtils.isBlank(jsonObject.getString("error_response"))){
				res.setResult("1");
				res.setResultNote("获取失败");
				return res;
			}

			res.put("data",jsonObject);
			JSONObject data = jsonObject.getJSONObject("resource_url_response");
			JSONObject data2 = data.getJSONObject("single_url_list");
			String mobile_url = data2.getString("mobile_url");
			String mobile_url2 = data2.getString("mobile_url")+"&resourceType=39998";
			jsonObject.getJSONObject("resource_url_response").getJSONObject("single_url_list").put("mobile_url",mobile_url2);
			res.put("data",jsonObject);
			res.put("url",req.getString("url"));
			res.put("resourceType",req.getString("resource_type"));
			res.put("pid",pid);
			res.setResult("0");
			res.setResultNote("操作成功");

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 多多进宝主题推广链接生成
	 * @param req
	 * @return
	 */
	@PostMapping("/DuoduoGenerate")
	@ResponseBody
	public ResJson DuoduoGenerate(@RequestBody ReqJson req,HttpServletRequest request) {
		ResJson res = new ResJson();
		try {
			String pid;
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("用户ID不能为空！");
				return res;
			}
			Member member = memberService.get(req.getString("uid"));
			if (member == null) {
				res.setResultNote("该用户不存在！");
				return res;
			}
			pid=member.getPddId();
			if(StringUtils.isBlank(member.getPddId())){
				//调用喵有券创建推广位接口给当前用户生成一个推广位id
				Map<String, String> params = Maps.newHashMap();
				params.put("pdname", MiaoyouquanUtils.pdname);
				params.put("number", "1");
				JSONObject jsonObject2 = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params);
				logger.debug("喵有券返回数据：" + jsonObject2.toString());
				if ("200".equals(jsonObject2.getString("code"))) {
					JSONObject dataObject=jsonObject2.getJSONObject("data");
					if(dataObject!=null){
						JSONArray pidList=dataObject.getJSONArray("p_id_list");
						if(pidList!=null && pidList.size()>0){
							member.setPddId(pidList.getJSONObject(0).getString("p_id"));
							memberService.save(member);
							pid=pidList.getJSONObject(0).getString("p_id");
						}
					}
				}
			}
			Map<String, String> params = Maps.newHashMap();
			params.put("pid", pid);
//			params.put("url", URLEncoder.encode(req.getString("url","UTF-8")));
			String[] theme_id_list = new String[]{"1", "7068"};
			params.put("theme_id_list", String.valueOf(theme_id_list));
			JSONObject jsonObject = MiaoyouquanUtils.duoduorouterAPI(MiaoyouquanUtils.router,MiaoyouquanUtils.generate, params);
			if(!StringUtils.isBlank(jsonObject.getString("error_response"))){
				res.setResult("1");
				res.setResultNote("获取失败");
				return res;
			}
			res.put("data",jsonObject);
			res.put("url",req.getString("url"));
			res.put("pid",pid);
			res.setResult("0");
			res.setResultNote("操作成功");

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 获取商家提现的openid和用户微信昵称
	 * @param req
	 * @return
	 */
	@PostMapping("/ForTxopenid")
	@ResponseBody
	public ResJson ForTxopenid(@RequestBody ReqJson req,HttpServletRequest request) {
		ResJson res = new ResJson();
		res.setResult("1");
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("UID不能为空！");
				return res;
			}
			Member Member=memberService.get(req.getUid());
			String openid="";
			openid=Member.getTxopenid();//获取openid
//			if(StringUtils.isBlank(openid)){//判断openid是否为空
				String appid="wxfd00b75fa13f1b76";
				String AppSecret="44838dd42a856513397bd1322f0d7641";
				String code=req.getString("code");

				res.put("code",code);
				WxpubOAuth.OAuthResult OAuthResult=WxpubOAuth.getOpenId(appid,AppSecret,code);
				openid=(String)OAuthResult.getOpenid();
				String accesstoken=(String)OAuthResult.getAccess_token();
				if(StringUtils.isBlank(openid)){
					System.out.println(OAuthResult);
					res.setResultNote("code过期，请刷新重试！");
					return  res;
				}
				String nickname=WxpubOAuth.getinfo(accesstoken,openid);

				res.put("nickname",nickname);
				if(StringUtils.isBlank(nickname)){
					System.out.println(OAuthResult);
					res.setResultNote("accesstoken过期，请刷新重试！");
					return  res;
				}
				Member.setTxopenid(openid);
				Member.setTxname(nickname);
				memberService.save(Member);//更新openid
//			}else {
//				res.setResultNote("该账号已有綁定！");
//				return  res;
//			}
			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	/**
	 * 微信企业支付
	 * @param req
	 * @return
	 */
	@PostMapping("/wxqyPay")
	@ResponseBody
	public ResJson wxqyPay(@RequestBody ReqJson req,HttpServletRequest request) {
		ResJson res = new ResJson();
		try {
			String openid="okob81ZY1kEUHibhhXn22MCg3-mU";
//			String openid=req.getString("openid");
			String payMoney=req.getString("payMoney");
			String orderId=req.getString("orderId");
			String desc="附近商圈商家提现，由于系统问题,未及时到账,敬请谅解";
//			String desc="邵世玉测试,晚点转回去";
			Map<String, String> body = WxPayUtils.wxqyPay(openid, payMoney,orderId,desc);
			String status = body.get("status");
			String msg = body.get("msg");
			if("1".equals(status)){
				res.setResultNote("提现失败："+msg);
				return res;
			}
			res.put("status", status);
			res.put("msg", msg);
			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 多麦联盟美团红包
	 * @return
	 */
	@PostMapping("/duomaiAmre")
	@ResponseBody
	public ResJson duomaiAmre(@RequestBody ReqJson req,HttpServletRequest request) {
		ResJson res = new ResJson();
		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("euid", req.getString("uid"));
//            String  url=MiaoyouquanUtils.track+getParams();
			Object jsonObject = MiaoyouquanUtils.duomaiAPI(MiaoyouquanUtils.track, params);
			res.put("url",jsonObject);
			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 分享绑定上下级关系
	 * @param req
	 * @return
	 */
	@PostMapping("/bindRelation")
	@ResponseBody
	public ResJson bindRelation(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败");
		try {
			if (!isBlank(req.getUid(), req.getString("inviteId"))) {
				Member member = memberService.get(req.getUid());
				Member invite = memberService.get(req.getString("inviteId"));
				if (member != null && invite != null) {
					if (member.getInvite() == null || wohuiId.equals(member.getInvite().getId())) {
						if (invite.getInvite() == null || !req.getUid().equals(invite.getInvite())) {
							// 调用三方接口
							List<WohuiEntity> list = Lists.newArrayList();
							list.add(new WohuiEntity("CardGUID", member.getId()));
							list.add(new WohuiEntity("SenderGUID", invite.getId()));
							JSONObject object = WohuiUtils.send(WohuiUtils.ChangeSender, list);
							if (!"0000".equals(object.getString("respCode"))) {
//								res.setResultNote("更换推荐人失败："+object.getString("respMsg"));
//								return res;
							} else {
								member.setInvite(invite);
								memberService.save(member);
							}
						}
					}
				}
			}
			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 云店铺产品-是否已有产品代理
	 * @param req
	 * @return
	 */
	@PostMapping("/msmCheck")
	@ResponseBody
	public ResJson msmCheck(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("province"), req.getString("city"), req.getString("source"), req.getString("goodsid"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("Province",req.getString("province")));
			list.add(new WohuiEntity("City", req.getString("city")));
			list.add(new WohuiEntity("District", req.getString("area"),false));
			list.add(new WohuiEntity("Source", req.getString("source")));
			list.add(new WohuiEntity("GoodsID", req.getString("goodsid")));
			JSONObject object = WohuiUtils.send(WohuiUtils.MSMGoodsIsHas, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResult("1");
				res.setResultNote("获取失败:"+object.getString("respMsg"));
				return res;
			}
			JSONArray array = object.getJSONArray("data");
			res.put("rowsCount",object.getString("rowsCount"));
			res.put("IsHas",array.getJSONObject(0).getString("IsHas"));

			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 信用卡申请记录
	 * @param req
	 * @return
	 */
	@PostMapping("/creditCardOrderList")
	@ResponseBody
	public ResJson creditCardOrderList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}
			CreditCardOrder creditCardOrder = new CreditCardOrder();
			if ("1".equals(req.getString("type"))) {
				creditCardOrder.setDataScope(" AND a.uid IN(SELECT id FROM t_member WHERE invite_id='"+req.getUid()+"') ");
			} else {
				creditCardOrder.setMember(new Member(req.getUid()));
			}
			Page<CreditCardOrder> page = creditCardOrderService.findPage(new Page<CreditCardOrder>(req.getPageNo(), req.getPageSize()), creditCardOrder);
			res.setTotalPage(page.getTotalPage());
			for (CreditCardOrder order : page.getList()) {
				Map<String, String> map = Maps.newHashMap();
				map.put("orderId", order.getId());
				map.put("title", order.getTitle());
				map.put("point", order.getPoint());
				map.put("createDate", DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(order.getCreateDate()));
				map.put("state", order.getOrderStatus());
				dataList.add(map);
			}

			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 极速申请信用卡
	 * @param req
	 * @return
	 */
	@PostMapping("/applyCreditCard")
	@ResponseBody
	public ResJson applyCreditCard(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("提交失败");
		try {
			if (isBlank(req.getUid(), req.getString("name"), req.getString("telephone"), req.getString("idcard"), req.getString("creditCardId"), req.getString("captcha"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			String captcha = getCaptcha(req.getString("telephone"));
			if (!req.getString("captcha").equals(captcha)) {
				res.setResultNote("验证码错误");
				return res;
			}

			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			CreditCard creditCard = creditCardService.get(req.getString("creditCardId"));
			if (creditCard == null || "1".equals(creditCard.getState())) {
				res.setResultNote("该信用卡不存在或已下架");
				return res;
			}

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("timestamp", new Date().getTime());
			jsonObject.put("phone", req.getString("telephone"));
			jsonObject.put("name", req.getString("name"));
			jsonObject.put("idcard", req.getString("idcard"));
			jsonObject.put("productCode", creditCard.getCode());
			JSONObject object = CreditCardUtils.send(CreditCardUtils.unionLogin, jsonObject.toString());
			if ("0".equals(object.getString("code"))) {
				JSONObject data = object.getJSONObject("data");
				if (data != null) {
					JSONObject content = data.getJSONObject("content");
					if (content != null) {
						String orderId = content.getString("orderId");
						String url = content.getString("url");

						if (StringUtils.isNotBlank(orderId)) {
							CreditCardOrder creditCardOrder = new CreditCardOrder();
							creditCardOrder.setIsNewRecord(true);
							creditCardOrder.setId(orderId);
							creditCardOrder.setMember(member);
							creditCardOrder.setCode(creditCard.getCode());
							creditCardOrder.setTitle(creditCard.getTitle());
							creditCardOrder.setIcon(creditCard.getIcon());
							creditCardOrder.setUrl(url);
							creditCardOrder.setPoint(creditCard.getPoint());
							creditCardOrderService.save(creditCardOrder);

							res.put("orderId", orderId);
							res.put("url", url);
							res.setResult("0");
							res.setResultNote("提交成功");

							removeCaptcha(req.getString("telephone"));
						}
					}
				}
			} else {
				res.setResultNote(object.getString("message"));
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 信用卡列表
	 * @param req
	 * @return
	 */
	@PostMapping("/creditCardList")
	@ResponseBody
	public ResJson creditCardList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			CreditCard creditCard = new CreditCard();
			creditCard.setState("0");
			Page<CreditCard> page = creditCardService.findPage(new Page<CreditCard>(req.getPageNo(), req.getPageSize()), creditCard);
			res.setTotalPage(page.getTotalPage());
			for (CreditCard card : page.getList()) {
				Map<String, String> map = Maps.newHashMap();
				map.put("id", card.getId());
				map.put("code", card.getCode());
				map.put("image", getRealImage(card.getIcon()));
				map.put("name", card.getTitle());
				map.put("integral", card.getPoint());
				dataList.add(map);
			}

			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 拼团订单详情
	 * @param req
	 * @return
	 */
	@PostMapping("/ptOrderDetail")
	@ResponseBody
	public ResJson ptOrderDetail(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("orderId"))) {
				res.setResultNote("订单号不能为空");
				return res;
			}
			GroupOrder order = groupOrderService.get(req.getString("orderId"));
			if (order == null) {
				res.setResultNote("订单不存在");
				return res;
			}
			res.put("status", order.getState());
			res.put("name", order.getUsername());
			res.put("telephone", order.getPhone());
			res.put("address", order.getAddress());
			res.put("shopId", order.getStore().getId());
			res.put("shopName", order.getStore().getTitle());
			res.put("shopTele", order.getStore().getPhone());
			res.put("orderNum", order.getId());
			res.put("productId", order.getProduct().getId());
			res.put("productImage", getRealImage(order.getProductIcon()));
			res.put("productName", order.getProductTitle());
			res.put("sku", order.getSkuName());
			res.put("integral", order.getPoint());
			res.put("price", order.getPrice());
			res.put("count", order.getQty());
			res.put("totalMoney", order.getAmount());
			res.put("serviceFee", order.getProxyPrice());
			res.put("freight", order.getFreight());
			res.put("couponMoney", order.getDiscount());
			res.put("payMoney", order.getAmount());
			res.put("remark", order.getRemarks());
			res.put("adtime", DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(order.getCreateDate()));
			res.put("payTime", order.getPayDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(order.getPayDate()) : "");
			res.put("fahuoTime", order.getSendDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(order.getSendDate()) : "");
			res.put("wanchengTime", order.getFinishDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(order.getFinishDate()) : "");
			res.put("checkTime", order.getRefundDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(order.getRefundDate()) : "");
			res.put("cancelReason", order.getCancelReason());
			res.put("cancelTime", order.getCancelDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(order.getCancelDate()) : "");
			res.put("expressCode", order.getExpressCode());
			res.put("expressName", order.getExpressName());
			res.put("payType", order.getPayType());
			res.put("receipt", order.getReceipt());
			res.put("expressNo", order.getExpressNo());
			res.put("thCode", order.getThCode());//提货码
			res.put("daimai", order.getDaimai() != null && StringUtils.isNotBlank(order.getDaimai().getId()) ? "1" : "0");
			List<String> imageList = Lists.newArrayList();
			String refundReason = "";
			String desc = "";
			String applyTime = "";
			String checkTime = "";
			GroupRefund groupRefund = new GroupRefund();
			groupRefund.setOrderId(order.getId());
			List<GroupRefund> list = groupRefundService.findList(groupRefund);
			if (!list.isEmpty()) {
				GroupRefund refund = list.get(0);
				res.put("refundMoney", refund.getAmount());
				if (StringUtils.isNotBlank(refund.getImages())) {
					for (String image : refund.getImages().split("\\|")) {
						if (StringUtils.isNotBlank(image)) {
							imageList.add(getRealImage(image));
						}
					}
				}
				refundReason = refund.getReason();
				desc = refund.getContent();
				applyTime = DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(refund.getCreateDate());
				checkTime =  refund.getAuditDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(refund.getAuditDate()) : "";
			}
			res.put("refundReason", refundReason);
			res.put("desc", desc);
			res.put("imageList", imageList);
			res.put("applyTime", applyTime);
			res.put("checkTime", checkTime);


			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 拼团订单列表
	 * @param req
	 * @return
	 */
	@PostMapping("/groupOrderList")
	@ResponseBody
	public ResJson groupOrderList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}
			// 获取订单各类型数量
			// 订单状态0-待付，1-待发，2-待收，3-待评，4-已评，5-取消，6-退款中，7-已退款
			String count0 = "0";// 待付订单数量
			String count1 = "0";// 待发订单数量
			String count2 = "0";// 待收订单数量
			String count3 = "0";// 待评价订单数量
			String count4 = "0";// 已完成订单数量
			String count5 = "0";// 取消订单数量
			String count6 = "0";// 售后订单数量
			List<Map<String,Object>> list = groupOrderService.executeSelectSql("SELECT a.state state,COUNT(*) count FROM t_group_order a WHERE "+("0".equals(req.getString("userType")) ? "a.uid = '"+req.getUid()+"' " : " a.uid IN (SELECT id FROM t_member WHERE invite_id='"+req.getString("uid")+"')")+" AND pg_order='0' GROUP BY a.state ");
			if (list != null && !list.isEmpty()) {
				for (Map<String, Object> map : list) {
					String state = map.get("state").toString();
					if ("0".equals(state)) {
						count0 = map.get("count").toString();
					} else if ("1".equals(state)) {
						count1 = map.get("count").toString();
					} else if ("2".equals(state)) {
						count2 = map.get("count").toString();
					} else if ("3".equals(state)) {
						count3 = map.get("count").toString();
					} else if ("4".equals(state)) {
						count4 = map.get("count").toString();
					} else if ("5".equals(state)) {
						count5 = map.get("count").toString();
					} else if ("6".equals(state)) {
						count6 = map.get("count").toString();
					}
				}
			}
			res.put("count0", count0);
			res.put("count1", count1);
			res.put("count2", count2);
			res.put("count3", count3);
			res.put("count4", count4);
			res.put("count5", count5);
			res.put("count6", count6);

			GroupOrder groupOrder = new GroupOrder();
			String dataScope = "";
			if ("1".equals(req.getString("userType"))) {// 客户订单
				dataScope += " AND a.uid IN (SELECT m.id FROM t_member m WHERE m.invite_id = '"+req.getUid()+"') ";
			} else {// 本人订单
				groupOrder.setMember(new Member(req.getUid()));
			}
			// 类型：空-全部,0-待付，1-待发，2-待收，3-待评价，4-已完成，5-取消
			/*if (StringUtils.isNotBlank(req.getString("type"))) {
				if ("6".equals(req.getString("type"))) {
					dataScope += " AND (a.state = '6' OR a.state = '7') ";
				} else {
					groupOrder.setState(req.getString("type"));
				}
			}*/
			groupOrder.setPgOrder("0");
			groupOrder.setState(req.getString("type"));
			groupOrder.setDataScope(dataScope);
			Page<GroupOrder> page = groupOrderService.findPage(new Page<>(req.getPageNo(), req.getPageSize()), groupOrder);
			res.setTotalPage(page.getTotalPage());
			for (GroupOrder order : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("orderId", order.getId());
				map.put("shopName", order.getStore().getTitle());
				map.put("orderNum", order.getId());
				map.put("status", order.getState());
				map.put("isProxy", order.getProxyType());
				map.put("payMoney", order.getAmount());
				map.put("productId", order.getProduct().getId());
				map.put("coverImage", getRealImage(order.getProductIcon()));
				map.put("productCode", order.getProductCode());
				map.put("productName", order.getProductTitle());
				map.put("specification", order.getSkuName());
				map.put("integral", order.getPoint());
				map.put("price", order.getPrice());
				map.put("count", order.getQty());
				map.put("thCode", order.getThCode());
				map.put("daimai", order.getDaimai() != null && StringUtils.isNotBlank(order.getDaimai().getId()) ? "1" : "0");
				dataList.add(map);
			}

			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}


	/**
	 * 拼团列表
	 * @param req
	 * @return
	 */
	@PostMapping("/groupList")
	@ResponseBody
	public ResJson groupList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}
			// 获取订单各类型数量
			// 状态 0进行中 1拼团成功 2拼团失败
			String count0 = "0";//
			String count1 = "0";//
			String count2 = "0";//
			List<Map<String,Object>> list = productGroupService.executeSelectSql("SELECT a.state state,COUNT(*) count FROM t_product_group a WHERE a.uid = '"+req.getUid()+"' GROUP BY a.state ");
			if (list != null && !list.isEmpty()) {
				for (Map<String, Object> map : list) {
					String state = map.get("state").toString();
					if ("0".equals(state)) {
						count0 = map.get("count").toString();
					} else if ("1".equals(state)) {
						count1 = map.get("count").toString();
					} else if ("2".equals(state)) {
						count2 = map.get("count").toString();
					}
				}
			}
			res.put("count0", count0);
			res.put("count1", count1);
			res.put("count2", count2);
			ProductGroup productGroup = new ProductGroup();
			productGroup.setMember(new Member(req.getString("uid")));
			if (!StringUtils.isBlank(req.getString("state"))) {//
				productGroup.setState(req.getString("state"));
			}
			Page<ProductGroup> page = productGroupService.findPage(new Page<>(req.getPageNo(), req.getPageSize()), productGroup);
			res.setTotalPage(page.getTotalPage());
			for (ProductGroup order : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				Product product = productService.get(order.getProduct().getId());
				map.put("groupid", order.getId());
				map.put("shopName", product.getStore().getTitle());
				map.put("status", order.getState());
				map.put("productId", product.getId());
				map.put("coverImage", getRealImage(product.getIcon()));
				map.put("productName", product.getTitle());
				map.put("yjprice", product.getPrice());
				map.put("ptprice", product.getGroupPrice());
				int Timest=0;
				Timest=Integer.parseInt(order.getTimes());
				long times = (DateUtil.addHours(order.getCreateDate(), Timest).getTime() - new Date().getTime()) / 1000;
				map.put("times", "1".equals(order.getState()) ? "0" : times + "");
				map.put("RenNum", product.getPtRenNum());
				GroupOrder gp=new GroupOrder();
				gp.setState("1");
				gp.setGroupId(order.getId());
				map.put("canNum", order.getCanNum());
				dataList.add(map);
			}
			res.setResult("0");
			res.setDataList(dataList);
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 旅游列表接口
	 * @param req
	 * @return
	 */
	@PostMapping("/TravelList")
	@ResponseBody
	public ResJson TravelList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			JSONObject object = WohuiUtils.send(WohuiUtils.TravelList, list);
			JSONArray array = object.getJSONArray("data");
			BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//
			int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
			res.setTotalPage(renewNum);
			res.put("rowsCount",object.getString("rowsCount"));
			res.put("totalCount",object.getString("totalCount"));
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
				return res;
			} else {

				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 奖品列表-（非砍一刀）
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPrizeList")
	@ResponseBody
	public ResJson ForPrizeList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			JSONObject object = WohuiUtils.send(WohuiUtils.PrizeList, list);
			JSONArray array = object.getJSONArray("data");
			BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//
			int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
			res.setTotalPage(renewNum);
			res.put("rowsCount",object.getString("rowsCount"));
			res.put("totalCount",object.getString("totalCount"));
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
				return res;
			} else {

				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 奖品领取-发货接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPrizeToGetSend")
	@ResponseBody
	public ResJson ForPrizeToGetSend(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			String Remark ="";
			if (isBlank(req.getString("PGUID"))) {
				res.setResultNote("奖品编号不能为空");
				return res;
			}
			if (!isBlank(req.getString("Remark"))) {
				Remark =req.getString("Remark");
			}
            if (StringUtils.isBlank(req.getString("addrId"))) {
                res.setResultNote("收货地址ID不能为空！");
                return res;
            }
            Address addr = addressService.get(req.getString("addrId"));
            if (addr == null) {
                res.setResultNote("该收货地址不存在！");
                return res;
            }
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("PGUID", req.getString("PGUID")));
			list.add(new WohuiEntity("RealName", addr.getUsername()));
			list.add(new WohuiEntity("Phone", addr.getPhone()));
			list.add(new WohuiEntity("Province", addr.getProvince()));
			list.add(new WohuiEntity("City", addr.getCity()));
			list.add(new WohuiEntity("District", addr.getArea(), false));
			list.add(new WohuiEntity("Address", addr.getDetails(), false));
			list.add(new WohuiEntity("Remark", Remark, false));
			JSONObject object = WohuiUtils.send(WohuiUtils.PrizeToGetSend, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 奖品领取-回购接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPrizeToGetBack")
	@ResponseBody
	public ResJson ForPrizeToGetBack(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			String Remark ="";
			if (isBlank(req.getString("PGUID"))) {
				res.setResultNote("奖品编号不能为空");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("PGUID", req.getString("PGUID")));
			JSONObject object = WohuiUtils.send(WohuiUtils.PrizeToGetBack, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 惠康云店分-兑换产品 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForHKYDScoreExchangeProduct")
	@ResponseBody
	public ResJson ForHKYDScoreExchangeProduct(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空");
				return res;
			}
			if (isBlank(req.getString("productname"))) {
				res.setResultNote("产品的名称不能为空");
				return res;
			}if (isBlank(req.getString("productnum"))) {
				res.setResultNote("产品的数量不能为空");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("ProductName", req.getString("productname")));
			list.add(new WohuiEntity("ProductNum", req.getString("productnum")));
			JSONObject object = WohuiUtils.send(WohuiUtils.HKYDScoreExchangeProduct, list);
			JSONArray data = object.getJSONArray("data");
			JSONObject obj = data.getJSONObject(0);


			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.put("PrizeGUID",obj.getString("PrizeGUID"));//PrizeGUID 为 奖品编号，兑换产品成功后，跳转到奖品领取页面
				res.put("PrizeFee",obj.getString("PrizeFee"));//PrizeGUID 为 奖品金额
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 惠康云店分-兑换奖金 接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForHKYDScoreExchangeMoney")
	@ResponseBody
	public ResJson ForHKYDScoreExchangeMoney(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空");
				return res;
			}
			if (isBlank(req.getString("score"))) {
				res.setResultNote("兑换分数不能为空");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("Score", req.getString("score")));
			JSONObject object = WohuiUtils.send(WohuiUtils.HKYDScoreExchangeMoney, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 云店铺购物券明细列表
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCESQLogList")
	@ResponseBody
	public ResJson ForCESQLogList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("类型不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("Type", req.getString("type")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			JSONObject object = WohuiUtils.send(WohuiUtils.CESQLogList, list);
			JSONArray array = object.getJSONArray("data");
			BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//
			int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
			res.setTotalPage(renewNum);
			res.put("rowsCount",object.getString("rowsCount"));
			res.put("totalCount",object.getString("totalCount"));
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
				return res;
			} else {

				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 专属产品(鬼谷回春堂/血德平)购物券明细列表
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPSSQLogList")
	@ResponseBody
	public ResJson ForPSSQLogList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("类型不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("Type", req.getString("type")));
			list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
			list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
			JSONObject object = WohuiUtils.send(WohuiUtils.PSSQLogList, list);
			JSONArray array = object.getJSONArray("data");
			BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//
			int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
			res.setTotalPage(renewNum);
			res.put("rowsCount",object.getString("rowsCount"));
			res.put("totalCount",object.getString("totalCount"));
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
				return res;
			} else {

				List<Map<String, Object>> dataList = Lists.newArrayList();
				if(array != null && !array.isEmpty()){
					res.setDataList(array);
				}else{
					res.setDataList(dataList);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增9/04
	 *产品服务站-开通惠康云店接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPSSOpenHKYD")
	@ResponseBody
	public ResJson ForPSSOpenHKYD(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("phone"))) {
				res.setResultNote("需要开通的账号不能为空");
				return res;
			}
			List<WohuiEntity> entityList = Lists.newArrayList();
			entityList.add(new WohuiEntity("Phone", req.getString("phone")));
			JSONObject object3 = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, entityList);
			if (!"0000".equals(object3.getString("respCode"))) {
				res.setResultNote("需要开通的账号不存在");
				return res;
			}
			JSONArray jsonArray = object3.getJSONArray("data");
			JSONObject whuser = jsonArray.getJSONObject(0);
			String uid=whuser.getString("C_GUID");
			if (isBlank(req.getString("pssguid"))) {
				res.setResultNote("产品服务站账号不能为空");
				return res;
			}
			if (isBlank(req.getString("type"))) {
				res.setResultNote("类型不能为空");
				return res;
			}
			if (isBlank(req.getString("goodsid"))) {
				res.setResultNote("商品ID不能为空");
				return res;
			}
			if (isBlank(req.getString("province"))) {
				res.setResultNote("省份不能为空");
				return res;
			}
			if (isBlank(req.getString("city"))) {
				res.setResultNote("城市不能为空");
				return res;
			}
			if (isBlank(req.getString("area"))) {
				res.setResultNote("县区不能为空");
				return res;
			}

			Member member = memberService.get(uid);
			if (member == null) {
				member = new Member();
				member.setIsNewRecord(true);
				member.setId(whuser.getString("C_GUID"));
				member.setNumber(whuser.getString("C_Number"));
				member.setRoles(whuser.getString("C_Roles"));
				member.setPhone(whuser.getString("C_Phone"));
				member.setNickname(StringUtils.isNotBlank(whuser.getString("C_RealName")) ? whuser.getString("C_RealName") : "用户" + StringUtils.right(whuser.getString("C_Phone"), 4));
				member.setPassword(whuser.getString("C_LoginPwd"));
				member.setProvince(whuser.getString("C_Province"));
				member.setCity(whuser.getString("C_City"));
				member.setArea(whuser.getString("C_District"));
				member.setState("0");
				member.setPoint("0");
				member.setInvite(new Member(whuser.getString("C_Sender")));
				memberService.save(member);
			}
			Product product = productService.get(req.getString("goodsid"));
			Store shop = storeService.get(product.getStore());
			ProductSku sku = null;
			ProductSku productSku = new ProductSku();
			productSku.setProduct(product);
			List<ProductSku> productSkuList = productSkuService.findList(productSku);
			sku = productSkuList.get(0);
			//订单商品表
			List<ProductOrder> orderList = Lists.newArrayList();
			List<OrderItem> orderItemList = Lists.newArrayList();// 订单项
			OrderItem item = new OrderItem();
			item.setId("");
			item.setProductId(product.getId());
			item.setSkuId(sku.getId());
			item.setProductCode(product.getCode());
			item.setProductTitle(product.getTitle());
			item.setProductIcon(product.getIcon());
			item.setIsDl(product.getIsDl());
			item.setIsYg(product.getIsYg());
			String goodstype="4";
			item.setGoodstype(goodstype);
			item.setSkuName(sku.getTitle());
			item.setQty(1);
			item.setPrice(sku.getPrice());
			item.setDiffprice("0");
			item.setPoint("0");
			item.setDiscount("0");
			orderItemList.add(item);

//			生成订单
			String bigOrderNum = OrderNumPrefix.totalId + IdGen.getOrderNo();
			ProductOrder productOrder = new ProductOrder();
			productOrder.setIsNewRecord(true);
			productOrder.setId(IdGen.getOrderNo());
			productOrder.setMember(member);
			productOrder.setDaimai(null);
			productOrder.setStore(shop);
			productOrder.setTotalId(bigOrderNum);
			productOrder.setFreight("0");
			productOrder.setGiftprice("0");//赠品需支付价格
			productOrder.setGwbprice("0");//购物币优惠价
			productOrder.setAmount(sku.getPrice());//订单总价
			productOrder.setMoney(sku.getPrice());// 订单结算价=商品结算价+运费+赠品需支付价格
			productOrder.setProxyType("0");
			productOrder.setProxyPrice("0");
			productOrder.setUsername("");
			productOrder.setPhone("");
			productOrder.setProvince(req.getString("province"));
			productOrder.setCity(req.getString("city"));
			productOrder.setMarea(req.getString("area"));
			productOrder.setAddress(req.getString("province") + req.getString("city") + req.getString("area") + "(用户自提)");
			productOrder.setState("0");
			productOrder.setIsHot("0");
			productOrder.setRemarks("");
			productOrder.setReceipt("");
			productOrder.setCreateDate(new Date());
			productOrder.setOrderItemList(orderItemList);
			productOrder.setPoint("0");
			productOrder.setPrice(sku.getPrice());
			productOrder.setDiscount("0");
			if(!orderItemList.isEmpty()){
				orderList.add(productOrder);
			}
			productOrderService.insert(orderList);

			res.put("orderNum", productOrder.getId());
			res.put("amount", sku.getPrice());
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("OrderNO", productOrder.getId()));
			list.add(new WohuiEntity("CardGUID", uid));
			list.add(new WohuiEntity("Type", req.getString("type")));
			list.add(new WohuiEntity("Money", sku.getPrice()));
			list.add(new WohuiEntity("PSSGUID",req.getString("pssguid")));

			JSONObject object = WohuiUtils.send(WohuiUtils.PSSOpenHKYD, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				ProductOrder productOrder2 = productOrderService.get(productOrder.getId());
				productOrder2.setState("1");
				productOrder2.setPayType("5");
				productOrder2.setPayDate(new Date());
				productOrderService.pay(productOrder2);
				productOrder2.setState("3");
				productOrder2.setFinishDate(new Date());
				productOrderService.finish(productOrder2);
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增9/04
	 *云端快递超市-开通云店铺接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForCESOpenCS")
	@ResponseBody
	public ResJson ForCESOpenCS(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("phone"))) {
				res.setResultNote("需要开通的账号不能为空");
				return res;
			}
			List<WohuiEntity> entityList = Lists.newArrayList();
			entityList.add(new WohuiEntity("Phone", req.getString("phone")));
			JSONObject object3 = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, entityList);
			if (!"0000".equals(object3.getString("respCode"))) {
				res.setResultNote("需要开通的账号不存在");
				return res;
			}
			JSONArray jsonArray = object3.getJSONArray("data");
			JSONObject whuser = jsonArray.getJSONObject(0);
			String uid=whuser.getString("C_GUID");
			if (StringUtils.isNotBlank(whuser.getString("C_Roles"))) {
				String[] roles = whuser.getString("C_Roles").split(",");
				List<String> rolesList = Arrays.asList(roles);
//				rolesList.remove("零售云店铺");
				if (rolesList.contains("云店铺")) {
					res.setResultNote("您已经是云店铺身份，无需重复开通！");
					return res;
				}
			}
			if (isBlank(req.getString("cesguid"))) {
				res.setResultNote("云端快递超市账号不能为空");
				return res;
			}
			if (isBlank(req.getString("goodsid"))) {
				res.setResultNote("商品ID不能为空");
				return res;
			}
			if (isBlank(req.getString("province"))) {
				res.setResultNote("省份不能为空");
				return res;
			}
			if (isBlank(req.getString("city"))) {
				res.setResultNote("城市不能为空");
				return res;
			}
			if (isBlank(req.getString("area"))) {
				res.setResultNote("县区不能为空");
				return res;
			}

			Member member = memberService.get(uid);
			if (member == null) {
				member = new Member();
				member.setIsNewRecord(true);
				member.setId(whuser.getString("C_GUID"));
				member.setNumber(whuser.getString("C_Number"));
				member.setRoles(whuser.getString("C_Roles"));
				member.setPhone(whuser.getString("C_Phone"));
				member.setNickname(StringUtils.isNotBlank(whuser.getString("C_RealName")) ? whuser.getString("C_RealName") : "用户" + StringUtils.right(whuser.getString("C_Phone"), 4));
				member.setPassword(whuser.getString("C_LoginPwd"));
				member.setProvince(whuser.getString("C_Province"));
				member.setCity(whuser.getString("C_City"));
				member.setArea(whuser.getString("C_District"));
				member.setState("0");
				member.setPoint("0");
				member.setInvite(new Member(whuser.getString("C_Sender")));
				memberService.save(member);
			}
			Product product = productService.get(req.getString("goodsid"));
			Store shop = storeService.get(product.getStore());
			ProductSku sku = null;
			ProductSku productSku = new ProductSku();
			productSku.setProduct(product);
			List<ProductSku> productSkuList = productSkuService.findList(productSku);
			sku = productSkuList.get(0);
			//订单商品表
			List<ProductOrder> orderList = Lists.newArrayList();
			List<OrderItem> orderItemList = Lists.newArrayList();// 订单项
			OrderItem item = new OrderItem();
			item.setId("");
			item.setProductId(product.getId());
			item.setSkuId(sku.getId());
			item.setProductCode(product.getCode());
			item.setProductTitle(product.getTitle());
			item.setProductIcon(product.getIcon());
			item.setIsDl(product.getIsDl());
			item.setIsYg(product.getIsYg());
			item.setGoodstype("0");
			item.setSkuName(sku.getTitle());
			item.setQty(1);
			item.setPrice(sku.getPrice());
			item.setPoint("0");
			item.setDiffprice("0");
			item.setDiscount("0");
			orderItemList.add(item);

//			生成订单
			String bigOrderNum = OrderNumPrefix.totalId + IdGen.getOrderNo();
			ProductOrder productOrder = new ProductOrder();
			productOrder.setIsNewRecord(true);
			productOrder.setId(IdGen.getOrderNo());
			productOrder.setMember(member);
			productOrder.setDaimai(null);
			productOrder.setStore(shop);
			productOrder.setTotalId(bigOrderNum);
			productOrder.setFreight("0");
			productOrder.setGiftprice("0");//赠品需支付价格
			productOrder.setGwbprice("0");//购物币优惠价
			productOrder.setAmount(sku.getPrice());//订单总价
			productOrder.setMoney(sku.getPrice());// 订单结算价=商品结算价+运费+赠品需支付价格
			productOrder.setProxyType("0");
			productOrder.setProxyPrice("0");
			productOrder.setUsername("");
			productOrder.setPhone("");
			productOrder.setProvince(req.getString("province"));
			productOrder.setCity(req.getString("city"));
			productOrder.setMarea(req.getString("area"));
			productOrder.setAddress(req.getString("province") + req.getString("city") + req.getString("area") + "(用户自提)");
			productOrder.setState("0");
			productOrder.setIsHot("0");
			productOrder.setRemarks("");
			productOrder.setReceipt("");
			productOrder.setCreateDate(new Date());
			productOrder.setOrderItemList(orderItemList);
			productOrder.setPoint("0");
			productOrder.setPrice(sku.getPrice());
			productOrder.setDiscount("0");
			if(!orderItemList.isEmpty()){
				orderList.add(productOrder);
			}
			productOrderService.insert(orderList);

			res.put("orderNum", productOrder.getId());
			res.put("amount", sku.getPrice());
			// 调用三方接口
			String type ="";
			if("d0cb53f7001b46b9a8065f6d689296c4".equals(req.getString("goodsid"))){//背包套餐
				type="10";
			}else if("1bf7c242ab2a45c09713b273dedd53f8".equals(req.getString("goodsid"))){//负离子玉石床垫单温控加热床垫1.5米X1.9米
				type="20";
			}
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("OrderNO", productOrder.getId()));
			list.add(new WohuiEntity("CardGUID", uid));
			list.add(new WohuiEntity("Type", type));
			list.add(new WohuiEntity("Money", sku.getPrice()));
			list.add(new WohuiEntity("CESGUID", req.getString("cesguid")));

			JSONObject object = WohuiUtils.send(WohuiUtils.CESOpenCS, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				ProductOrder productOrder2 = productOrderService.get(productOrder.getId());
				productOrder2.setState("1");
				productOrder2.setPayType("5");
				productOrder2.setPayDate(new Date());
				productOrderService.pay(productOrder2);
				productOrder2.setState("3");
				productOrder2.setFinishDate(new Date());
				productOrderService.finish(productOrder2);
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增9/20
	 *赠品签收接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPrizeSureSign")
	@ResponseBody
	public ResJson ForPrizeSureSign(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("PGUID"))) {
				res.setResultNote("奖品编号不能为空");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("PGUID", req.getString("PGUID")));
			JSONObject object = WohuiUtils.send(WohuiUtils.PrizeSureSign, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增2022/5/29
	 *奖品领取-转免费接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPrizeToFree")
	@ResponseBody
	public ResJson ForPrizeToFree(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (isBlank(req.getString("PGUID"))) {
				res.setResultNote("奖品编号不能为空");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("PGUID", req.getString("PGUID")));
			JSONObject object = WohuiUtils.send(WohuiUtils.PrizeToFree, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
			} else {
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 *消费券-购买申请接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForXFQApply")
	@ResponseBody
	public ResJson ForXFQApply(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("money"))) {
				res.setResultNote("金额不能为空！");
				return res;
			}

			String orderId ="XFQ" + IdGen.getOrderNo();//消费券支付单号
			Xfq o = new Xfq();
			o.setId(orderId);
			o.setGoodsnum("1");
			o.setCreatedate(new Date());
			o.setMoney(req.getString("money"));
			o.setMember(new Member(req.getString("uid")));
			o.setState("0");
			xfqMapper.insert(o);
			res.put("goodsnum",o.getGoodsnum());
			res.put("money",o.getMoney());
			res.put("orderno",o.getId());
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增2022/05/29
	 *VIP支付申请接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForVIPApply")
	@ResponseBody
	public ResJson ForVIPApply(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			String orderId ="VIP" + IdGen.getOrderNo();//支付单号
			Vip o = new Vip();
			o.setId(orderId);
			o.setGoodsnum("1");
			o.setCreateDate(new Date());
			o.setMoney("199");
			o.setMember(new Member(req.getString("uid")));
			o.setState("0");
			vipMapper.insert(o);
			res.put("money",o.getMoney());
			res.put("orderno",o.getId());
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 新增10/23
	 *赠品支付申请接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForPrizeApply")
	@ResponseBody
	public ResJson ForPrizeApply(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("PGUID"))) {
				res.setResultNote("奖品编号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("money"))) {
				res.setResultNote("综合服务费金额不能为空！");
				return res;
			}

			Prize prize = new Prize();
			prize = prizeService.getGguid(req.getString("PGUID"));

			if (prize != null) {
				BigDecimal money = new BigDecimal(req.getString("money"));
				res.put("goodsnum","1");
				res.put("money",prize.getMoney());
				res.put("orderno",prize.getId());
				res.setResult("0");
				res.setResultNote("获取成功");
				return res;
			}
			String orderId ="JP" + IdGen.getOrderNo();//赠品支付单号
			Prize o = new Prize();
			o.setId(orderId);
			o.setGoodsnum("1");
			o.setGguid(req.getString("PGUID"));
			o.setCreatedate(new Date());
			o.setMoney(req.getString("money"));
			o.setMember(new Member(req.getString("uid")));
			o.setState("0");
			prizeMapper.insert(o);
			res.put("goodsnum",o.getGoodsnum());
			res.put("money",o.getMoney());
			res.put("orderno",o.getId());
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
    /**
     * 奖品列表-全部
     * @param req
     * @return
     */
    @PostMapping("/ForKYDPrizeList")
    @ResponseBody
    public ResJson ForKYDPrizeList(@RequestBody ReqJson req) {
        ResJson res = new ResJson();
        res.setResultNote("获取失败");
        try {
            if (StringUtils.isBlank(req.getString("uid"))) {
                res.setResultNote("账号不能为空！");
                return res;
            }
            // 调用三方接口
            List<WohuiEntity> list = Lists.newArrayList();
            list.add(new WohuiEntity("CardGUID", req.getString("uid")));
            list.add(new WohuiEntity("PageIndex", req.getPageNo() + ""));
            list.add(new WohuiEntity("PageRows", req.getPageSize() + ""));
            JSONObject object = WohuiUtils.send(WohuiUtils.KYDPrizeList, list);
            JSONArray array = object.getJSONArray("data");
            BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//
            int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
            res.setTotalPage(renewNum);
            res.put("rowsCount",object.getString("rowsCount"));
			res.put("totalCount",object.getString("totalCount"));
            if (!"0000".equals(object.getString("respCode"))) {
                res.setResultNote("获取失败："+object.getString("respMsg"));
				return res;
            } else {

                List<Map<String, Object>> dataList = Lists.newArrayList();
                if(array != null && !array.isEmpty()){
                    res.setDataList(array);
                }else{
                    res.setDataList(dataList);
                }
                res.setResult("0");
                res.setResultNote("获取成功");
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return res;
    }
    /**
     * 奖品列表-今天
     * @param req
     * @return
     */
    @PostMapping("/ForKYDPrizeListToday")
    @ResponseBody
    public ResJson ForKYDPrizeListToday(@RequestBody ReqJson req) {
        ResJson res = new ResJson();
        res.setResultNote("获取失败");
        try {
            if (StringUtils.isBlank(req.getString("uid"))) {
                res.setResultNote("账号不能为空！");
                return res;
            }
            // 调用三方接口
            List<WohuiEntity> list = Lists.newArrayList();
            list.add(new WohuiEntity("CardGUID", req.getString("uid")));
            JSONObject object = WohuiUtils.send(WohuiUtils.KYDPrizeListToday, list);
            JSONArray array = object.getJSONArray("data");
            BigDecimal fee = new BigDecimal(object.getIntValue("totalCount")).divide(new BigDecimal(req.getPageSize()));//
            int renewNum  = (int) fee.setScale( 0, BigDecimal.ROUND_UP ).longValue(); // 向上取整
            res.setTotalPage(renewNum);
            res.put("rowsCount",object.getString("rowsCount"));
            if (!"0000".equals(object.getString("respCode"))) {
                res.setResultNote("获取失败："+object.getString("respMsg"));
				return res;
            } else {

                List<Map<String, Object>> dataList = Lists.newArrayList();
                if(array != null && !array.isEmpty()){
                    res.setDataList(array);
                }else{
                    res.setDataList(dataList);
                }
                res.setResult("0");
                res.setResultNote("获取成功");
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return res;
    }
	/**
	 * 爆品奖励-领取接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForBPPrizeToGet")
	@ResponseBody
	public ResJson ForBPPrizeToGet(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("uid"))) {
				res.setResultNote("账号不能为空！");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("奖品类型不能为空！");
				return res;
			}
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("CardGUID", req.getString("uid")));
			list.add(new WohuiEntity("Type", req.getString("type")));
			JSONObject object = WohuiUtils.send(WohuiUtils.BPPrizeToGet, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote(object.getString("respMsg"));
				return res;
			}
			res.setResult("0");
			if("10".equals(req.getString("type"))){
				res.setResultNote("领取成功，获得"+array.getJSONObject(0).getString("BPP_Money")+"爆品购物券");
			}else{
				res.setResultNote("领取成功，获得"+array.getJSONObject(0).getString("BPP_Money")+"旅游基金");
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
    /**
     * 奖品列表-领取（砍一刀）接口
     * @param req
     * @return
     */
    @PostMapping("/ForKYDPrizeListToGet")
    @ResponseBody
    public ResJson ForKYDPrizeListToGet(@RequestBody ReqJson req) {
        ResJson res = new ResJson();
        res.setResultNote("获取失败");
        try {
            if (StringUtils.isBlank(req.getString("uid"))) {
                res.setResultNote("账号不能为空！");
                return res;
            }
            // 调用三方接口
            List<WohuiEntity> list = Lists.newArrayList();
            list.add(new WohuiEntity("CardGUID", req.getString("uid")));
            JSONObject object = WohuiUtils.send(WohuiUtils.KYDPrizeListToGet, list);
            JSONArray array = object.getJSONArray("data");
            if (!"0000".equals(object.getString("respCode"))) {
                res.setResultNote("获取失败："+object.getString("respMsg"));
				return res;
            }
            res.setResult("0");
            res.setResultNote("获取成功");

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return res;
    }
	/**
	 * 砍一刀系统配置信息接口
	 * @param req
	 * @return
	 */
	@PostMapping("/ForKYDConfig")
	@ResponseBody
	public ResJson ForKYDConfig(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			// 调用三方接口
			List<WohuiEntity> list = Lists.newArrayList();
			JSONObject object = WohuiUtils.send(WohuiUtils.KYDConfig, list);
			JSONArray array = object.getJSONArray("data");
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote("获取失败："+object.getString("respMsg"));
				return res;
			}
			res.setDataList(array);
			res.setResult("0");
			res.setResultNote("获取成功");

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 拼团下单
	 * @param req
	 * @return
	 */
	@PostMapping("/addGroupOrder")
	@ResponseBody
	public ResJson addGroupOrder(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("提交失败");
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}
			if (StringUtils.isBlank(req.getString("productId"))) {
				res.setResultNote("商品ID不能为空");
				return res;
			}
			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			if ("1".equals(member.getState())) {
				res.setResultNote("用户被冻结");
				return res;
			}
			Product product = productService.get(req.getString("productId"));
			if (product == null || "1".equals(product.getState()) || !"1".equals(product.getAuditState())) {
				res.setResultNote("商品不存在或已下架");
				return res;
			}

			// 类型：0-不支付开团，1-支付开团 2-参团
			if ("0".equals(req.getString("type"))) {
				ProductGroup productGroup = new ProductGroup();
				productGroup.setMember(member);
				productGroup.setProduct(product);
				productGroup.setState("0");
				productGroup.setCreateDate(new Date());
//				productGroup.setTimes(product.getTimes());
//				productGroup.setPtRenNum(product.getPtRenNum());
//				productGroup.setIsMradd(product.getIsMradd());
				productGroup.setType("0");//不支付开团
				productGroupService.save(productGroup);
			} else {
				Address addr = addressService.get(req.getString("addrId"));
				if (addr == null) {
					res.setResultNote("该收货地址不存在！");
					return res;
				}
				// 判断代买人
				Member rec = null;
				BigDecimal proxyPrice = BigDecimal.ZERO;// 代理费
				Area area = null;
				if("1".equals(req.getString("isDaimai"))){//是代买
					if (StringUtils.isBlank(req.getString("telephone"))) {
						res.setResultNote("手机号不能为空！");
						return res;
					}
					rec = memberService.getByPhone(req.getString("telephone"));
					if (rec == null) {
						res.setResultNote("被代买手机号不存在");
						return res;
					}
				}
				// 判断代理
				if("1".equals(req.getString("isProxy"))){//是单品代理
					if (StringUtils.isBlank(req.getString("province"))) {
						res.setResultNote("请选择代理省份！");
						return res;
					}
					if (StringUtils.isBlank(req.getString("city"))) {
						res.setResultNote("请选择代理城市！");
						return res;
					}
					if (StringUtils.isBlank(req.getString("area"))) {
						res.setResultNote("请选择代理区县！");
						return res;
					}
					/*
					Object o = areaService.executeGetSql("SELECT area.id FROM sys_area area LEFT JOIN sys_area city ON area.parent_id = city.id LEFT JOIN sys_area province ON city.parent_id = province.id WHERE	area.`name` = '"+req.getString("area")+"' AND city.`name` = '"+req.getString("city")+"' AND province.`name` = '"+req.getString("province")+"'");
					if (o == null) {
						res.setResultNote("代理区域不存在");
						return res;
					}
					area = new Area(o.toString());

					// 判断单品代理是否存在
					String count = proxyLogService.executeGetSql("SELECT COUNT(*) FROM t_proxy_log WHERE `code` = '"+product.getCode()+"' AND ((province = '"+req.getString("province")+"' AND city = '"+req.getString("city")+"' AND area = '"+req.getString("area")+"') OR province = '全国')").toString();
					if (!"0".equals(count)) {
						res.setResultNote("该产品已被代理");
						return res;
					}
					*/
					// 获取代理费
					List<ProxyPrice> proxyPriceList = proxyPriceService.findList(new ProxyPrice());
					if (!proxyPriceList.isEmpty()) {
						proxyPrice = new BigDecimal(proxyPriceList.get(0).getPrice());
					}
				}

				// 判断库存
				ProductSku sku = null;

				ProductSku productSku = new ProductSku();
				productSku.setProduct(product);
				List<ProductSku> productSkuList = productSkuService.findList(productSku);
				for (ProductSku productSku2 : productSkuList) {
					if (productSku2.getId().equals(req.getString("ggId"))) {
						sku = productSku2;
					}
				}
				if (sku == null) {
					res.setResultNote("商品" + product.getTitle() + "不存在规格");
					return res;
				}


				// 判断库存
				int qty = req.getIntValue("count");
				int stock = sku.getStock();
				if (qty > stock) {
					res.setResultNote("商品" + product.getTitle() + "库存不足");
					return res;
				}

				BigDecimal totalAmount = BigDecimal.ZERO;// 总金额
				BigDecimal freight = BigDecimal.ZERO;// 店铺运费
				Store shop = storeService.get(product.getStore());
				if (StringUtils.isNotBlank(shop.getDistant())) {
					String[] distants = shop.getDistant().split(",");
					List<String> distantList = Arrays.asList(distants);
					if (distantList.contains(addr.getProvince()) && StringUtils.isNotBlank(shop.getFreight())) {
						freight = new BigDecimal(shop.getFreight());
					}
				}

				GroupOrder groupOrder = new GroupOrder();// 订单实例

				// 获取赠品
				ProductGift productGift = new ProductGift();
				productGift.setProduct(product);
				List<ProductGift> productGiftList = productGiftService.findList(productGift);
				for (ProductGift gift : productGiftList) {
					OrderGift orderGift = new OrderGift();
					orderGift.setId("");
					orderGift.setProduct(gift.getGift());
					orderGift.setProductTitle(gift.getProduct().getTitle());
					orderGift.setProductIcon(gift.getProduct().getIcon());
					orderGift.setQty(gift.getQty());
					orderGift.setPrice(gift.getProduct().getOldPrice());
					groupOrder.getOrderGiftList().add(orderGift);
				}

				if ("1".equals(req.getString("type"))) {
					ProductGroup productGroup = new ProductGroup();
					productGroup.setMember(member);
					productGroup.setProduct(product);
					productGroup.setState("0");
//					productGroup.setTimes(product.getTimes());
//					productGroup.setPtRenNum(product.getPtRenNum());
//					productGroup.setIsMradd(product.getIsMradd());
					productGroup.setType("1");
					productGroupService.save(productGroup);
					groupOrder.setGroupId(productGroup.getId());
				} else {
					if (StringUtils.isBlank(req.getString("groupId"))) {
						res.setResultNote("拼团ID不能为空");
						return res;
					}
					ProductGroup productGroup = productGroupService.get(req.getString("groupId"));
					if (productGroup == null || "2".equals(productGroup.getState())) {
						res.setResultNote("拼团不存在");
						return res;
					}
				}
				groupOrder.setIsNewRecord(true);
				String id=OrderNumPrefix.groupOrder + IdGen.getOrderNo();
				groupOrder.setId(id);
				groupOrder.setMember("1".equals(req.getString("isDaimai")) ? rec : member);
				groupOrder.setDaimai("1".equals(req.getString("isDaimai")) ? member : null);
				groupOrder.setProduct(product);
				groupOrder.setSkuId(sku.getId());
				groupOrder.setStore(shop);
				groupOrder.setProductCode(product.getCode());
				groupOrder.setProductTitle(product.getTitle());
				groupOrder.setProductIcon(product.getIcon());
				groupOrder.setPt_fwmoney(product.getPtFwmoney());
				groupOrder.setDlbt(product.getDlbt());
				groupOrder.setSkuName(sku.getTitle());
				groupOrder.setQty(qty);
				groupOrder.setPrice(sku.getGroupPrice());
				freight = freight.multiply(new BigDecimal(qty));
				groupOrder.setFreight(freight.toString());
				groupOrder.setMoney(new BigDecimal(sku.getAmount()).multiply(new BigDecimal(qty)).add(freight).toString());// 订单结算价=商品规格结算价*数量+运费
				groupOrder.setPoint(new BigDecimal(product.getPoint()).multiply(new BigDecimal(qty)).toString());
				groupOrder.setProxyType(req.getString("isProxy"));
				groupOrder.setProxyPrice(proxyPrice.toString());
				groupOrder.setRemarks(req.getString("remark"));
				groupOrder.setDiscount("0");
				groupOrder.setReceipt(req.getString("invoice"));
				groupOrder.setArea(area);
				groupOrder.setUsername(addr.getUsername());
				groupOrder.setPhone(addr.getPhone());
				groupOrder.setProvince(addr.getProvince());
				groupOrder.setCity(addr.getCity());
				groupOrder.setMarea(addr.getArea());
				groupOrder.setAddress(addr.getProvince() + addr.getCity() + addr.getArea() + addr.getDetails());
				groupOrder.setState("0");
				groupOrder.setPgOrder("0");
				groupOrder.setJrzjNum("0");
				totalAmount = totalAmount.add(new BigDecimal(sku.getGroupPrice()).multiply(new BigDecimal(qty))).add(freight).add(proxyPrice).setScale(2, BigDecimal.ROUND_DOWN);
				groupOrder.setAmount(totalAmount.toString());
				groupOrder.setCreateDate(new Date());
				groupOrderService.insert(groupOrder, req.getString("province"), req.getString("city"), req.getString("area"));

				res.put("orderNum", groupOrder.getId());
				res.put("amount", groupOrder.getAmount());
			}
			res.setResult("0");
			res.setResultNote("提交成功");
		} catch (Exception e) {
			res.setResultNote(e.getMessage());
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 获取团长地址
	 * @param req
	 * @return
	 */
	@PostMapping("/getGroupsAddress")
	@ResponseBody
	public ResJson getGroupsAddress(@RequestBody ReqJson req){
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("groups_id"))) {
				res.setResultNote("拼团id不能为空");
				return res;
			}
			ProductGroup resut	=  productGroupService.get(req.getString("groups_id"));
			Member member=resut.getMember();
			GroupOrder GroupOrder= new GroupOrder();
			GroupOrder.setGroupId(req.getString("groups_id"));
			GroupOrder.setMember(member);
			GroupOrder info = groupOrderService.get(GroupOrder);
			res.put("address",info.getAddress());
			res.setResult("获取成功");
			res.setResultNote("0");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 *返回团的成员信息订单信息
	 */
	@PostMapping("/getGroupsAndOrder")
	@ResponseBody
	public ResJson getGroupsAndOrder(@RequestBody ReqJson req){
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("groups_id"))) {
				res.setResultNote("拼团id不能为空");
				return res;
			}
			GroupOrder GroupOrder= new GroupOrder();
			GroupOrder.setGroupId(req.getString("groups_id"));
			if (!StringUtils.isBlank(req.getString("state"))) {//
				GroupOrder.setState(req.getString("state"));
			}
			GroupOrder.setState(req.getString("state"));
			Page<GroupOrder> page = groupOrderService.findPage(new Page<>(req.getPageNo(), req.getPageSize()), GroupOrder);
			res.setTotalPage(page.getTotalPage());
			List<Map<String, String>> GroupList = Lists.newArrayList();
			List<Map<String, String>> GroupOrderList = Lists.newArrayList();
			for (GroupOrder b : page.getList()) {
				//参团会员
				Map<String, String> map = Maps.newHashMap();
				Member member=b.getMember();
				map.put("gmuid", member.getId());
				map.put("gmphone", member.getPhone());
				map.put("gmname", member.getNickname());
				map.put("gmicon", member.getIcon());
				//订单
				GroupOrder order = groupOrderService.get(b.getId());
				if (order == null) {
					res.setResultNote("订单不存在");
					return res;
				}
				map.put("status", order.getState());
				map.put("shopId", order.getStore().getId());
				map.put("shopName", order.getStore().getTitle());
				map.put("shopTele", order.getStore().getPhone());
				map.put("orderNum", order.getId());
				map.put("th_code",order.getThCode());
				map.put("productId", order.getProduct().getId());
				map.put("productImage", getRealImage(order.getProductIcon()));
				map.put("productName", order.getProductTitle());
				map.put("sku", order.getSkuName());
				map.put("price", order.getPrice());
				map.put("count", String.valueOf(order.getQty()));
				map.put("totalMoney", order.getAmount());
				map.put("payMoney", order.getAmount());
				map.put("payTime", order.getPayDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(order.getPayDate()) : "");
				map.put("wanchengTime", order.getFinishDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(order.getFinishDate()) : "");
				map.put("expressCode", order.getExpressCode());
				map.put("expressName", order.getExpressName());
				map.put("expressNo", order.getExpressNo());
				map.put("pt_fwmoney", order.getPt_fwmoney());
				map.put("daimai", order.getDaimai() != null && StringUtils.isNotBlank(order.getDaimai().getId()) ? "1" : "0");
				GroupOrderList.add(map);
			}
			res.put("orderList",GroupOrderList);
			res.setResult("0");
			res.setResultNote("获取成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 *返回团的成员信息订单信息
	 */
	@PostMapping("/getgroupListinfo")
	@ResponseBody
	public ResJson getgroupListinfo(@RequestBody ReqJson req){
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("groups_id"))) {
				res.setResultNote("拼团id不能为空");
				return res;
			}
			GroupOrder GroupOrder= new GroupOrder();
			GroupOrder.setGroupId(req.getString("groups_id"));
			GroupOrder.setState("1");
			List<GroupOrder> list = groupOrderService.findList(GroupOrder);
			List<Map<String, String>> GroupOrderList = Lists.newArrayList();
			ProductGroup  productgroup=productGroupService.get(req.getString("groups_id"));
			int canNum= Integer.parseInt(productgroup.getCanNum());//参团人数
			res.put("ptRenNum",productgroup.getPtRenNum());//拼图人数
			int Timest=0;
			Timest=Integer.parseInt(productgroup.getTimes());
			long times = (DateUtil.addHours(productgroup.getCreateDate(), Timest).getTime() - new Date().getTime()) / 1000;
			res.put("times", "1".equals(productgroup.getState()) ? "0" : times + "");//时间
			Map<String, String> map1 = Maps.newHashMap();
			if(productgroup.getType().equals("0")){
				map1.put("gmuid", productgroup.getMember().getId());
				map1.put("gmphone", productgroup.getMember().getPhone());
				map1.put("gmname", productgroup.getMember().getNickname());
				map1.put("gmicon", productgroup.getMember().getIcon());
				map1.put("isgroup","1");
				canNum++;
				GroupOrderList.add(map1);
			}
			res.put("canNum",canNum);
			res.put("state", productgroup.getState());//拼团状态
			for (GroupOrder b : list) {
				//参团会员
				Map<String, String> map = Maps.newHashMap();
				Member member=b.getMember();
				map.put("gmuid", member.getId());
				map.put("gmphone", member.getPhone());
				map.put("gmname", member.getNickname());
				map.put("gmicon", member.getIcon());
				if(productgroup.getMember().getId().equals(member.getId())){
					map.put("isgroup","1");
				}else{
					map.put("isgroup","0");
				}
				GroupOrderList.add(map);
			}
			res.put("orderList",GroupOrderList);
			res.setResult("0");
			res.setResultNote("获取成功！");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 分享背景图
	 * @return
	 */
	@PostMapping("/sharePicture")
	@ResponseBody
	public ResJson sharePicture() {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			List<SharePicture> list = sharePictureService.findList(new SharePicture());
			if (!list.isEmpty()) {
				SharePicture sharePicture = list.get(0);
				if (StringUtils.isNotBlank(sharePicture.getImage())) {
					res.put("image", getRealImage(sharePicture.getImage()));
					res.setResult("0");
					res.setResultNote("获取成功");
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 运费计算
	 * @param req
	 * @return
	 */
	@PostMapping("/getFreight")
	@ResponseBody
	public ResJson getFreight(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("addressId"))) {
				res.setResultNote("地址不能为空");
				return res;
			}

			JSONArray shopList = req.getJSONArray("shopList");
			if (shopList == null || shopList.isEmpty()) {
				res.setResultNote("商家不能为空");
				return res;
			}
			Address address = addressService.get(req.getString("addressId"));
			if (address == null) {
				res.setResultNote("收货地址不存在");
				return res;
			}

			BigDecimal amount = BigDecimal.ZERO;
			BigDecimal voucher = BigDecimal.ZERO;// 代金券
			for (int i = 0; i < shopList.size(); i++) {
				JSONObject jsonObject = shopList.getJSONObject(i);
				Store store = storeService.get(jsonObject.getString("shopId"));
				if (store == null) {
					res.setResultNote("商家不存在");
					return res;
				}
				if (StringUtils.isNotBlank(store.getDistant()) && StringUtils.isNotBlank(store.getFreight())) {
					if (Arrays.asList(StringUtils.split(store.getDistant(), ",")).contains(address.getProvince())) {
						amount = amount.add(new BigDecimal(store.getFreight()).multiply(new BigDecimal(jsonObject.getIntValue("count"))));
					}
				}
			}

			List<WohuiEntity> entityList = Lists.newArrayList();
			entityList.add(new WohuiEntity("UGUID", address.getMember().getId()));
			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, entityList);
			if ("0000".equals(jsonObject.getString("respCode"))) {
				JSONArray jsonArray = jsonObject.getJSONArray("data");
				if (jsonArray != null && !jsonArray.isEmpty()) {
					JSONObject o = jsonArray.getJSONObject(0);
					voucher = o.getBigDecimal("C_DJQ").setScale(2, BigDecimal.ROUND_DOWN);
				}
			}
			res.put("totalAmount", amount.toString());
			res.put("voucher", voucher.toString());
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 附近商家生成订单
	 * @param req
	 * @return
	 */
	@PostMapping("/ShopGenerateorder")
	@ResponseBody
	public ResJson ShopGenerateorder(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败");
		try {
			if (isBlank(req.getUid(), req.getString("shopId"),req.getString("price"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			if(Double.valueOf(req.getString("price")) >5000.0){
				res.setResultNote("单笔金额不能大于5000");
				return res;
			}
			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			if ("1".equals(member.getState())) {
				res.setResultNote("用户被冻结");
				return res;
			}
			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null || !"2".equals(shop.getAuditState())) {
				res.setResultNote("商户未入住");
				return res;
			}
			if(!"0".equals(req.getString("coupontype"))){
				if (StringUtils.isBlank(req.getString("couponprice"))){
					res.setResultNote("消费券金额不符");
					return res;
				}
			}

			ShopbusOrder shopbusorder = new ShopbusOrder();
			shopbusorder.setIsNewRecord(true);
			shopbusorder.setId(OrderNumPrefix.BusinessOrder + IdGen.getOrderNo());
			shopbusorder.setMember(member);
			shopbusorder.setShop(shop);
			shopbusorder.setOrdertype("0");
			shopbusorder.setSmqfee("0");
			shopbusorder.setState("0");
			BigDecimal price = new BigDecimal(req.getString("price"));
			BigDecimal Hyrefee =  new BigDecimal(shop.getHyrebate()).multiply(price);//会员返利
			BigDecimal Ptrefee = (new BigDecimal(shop.getPtrebate()).subtract(new BigDecimal(0.01))).multiply(price);//平台返利
			BigDecimal fee = new BigDecimal(0).multiply(price);//付款时的手续费
			BigDecimal Amount =	new BigDecimal(req.getString("price")).subtract(Hyrefee).subtract(Ptrefee).subtract(fee);//总金额减会员返利，平台返利
			if("1".equals(req.getString("coupontype"))){
				price = price.subtract(new BigDecimal(req.getString("couponprice")));//减去购物券金额
				shopbusorder.setOrdertype("1");
				shopbusorder.setSmqfee(req.getString("couponprice"));
				if(price.compareTo(new BigDecimal(req.getString("couponprice"))) < 1){
					shopbusorder.setState("1");
				}
			}
			shopbusorder.setPrice(String.valueOf(price));
			BigDecimal giveup_fee = Amount.subtract(Amount.setScale(2,BigDecimal.ROUND_DOWN));//付款时的手续费
			shopbusorder.setHyrefee(Hyrefee.setScale(4,BigDecimal.ROUND_DOWN).toString());
			shopbusorder.setPtrefee(Ptrefee.setScale(4,BigDecimal.ROUND_DOWN).toString());
			shopbusorder.setFee(fee.setScale(4,BigDecimal.ROUND_DOWN).toString());
			shopbusorder.setGiveupfee(giveup_fee.setScale(4,BigDecimal.ROUND_DOWN).toString());
			shopbusorder.setState("0");
			shopbusorder.setAmount(Amount.setScale(2,BigDecimal.ROUND_DOWN).toString());
			shopbusorderService.pay(shopbusorder);
			if("1".equals(req.getString("coupontype"))){
					// 购物币支付
					if ("1".equals(shopbusorder.getOrdertype()) && new BigDecimal(req.getString("couponprice")).compareTo(BigDecimal.ZERO)  > 0 ) {
						List<WohuiEntity> entityList = Lists.newArrayList();
						entityList.add(new WohuiEntity("OrderNO", shopbusorder.getId()));
						entityList.add(new WohuiEntity("CardGUID", member.getId()));
						entityList.add(new WohuiEntity("XFQ", req.getString("couponprice")));
						entityList.add(new WohuiEntity("Source", "YD"));
						entityList.add(new WohuiEntity("Remark", ""));
						JSONObject result = WohuiUtils.send(WohuiUtils.XFQPay, entityList);
						if (!"0000".equals(result.getString("respCode"))) {
							res.setResult("1");
							res.setResultNote("我惠会员系统消费券大订单支付失败总单号：" +shopbusorder.getId()+ result.getString("respMsg"));
							return res;
						}
						if(price.compareTo(BigDecimal.ZERO)  == 0){
							ShopbusOrder shopbusorder2 =shopbusorderService.get(shopbusorder.getId());
							if (shopbusorder2 != null) {
								shopbusorder2.setPayType("2");
								shopbusorder2.setPayDate(new Date());
								shopbusorder2.setState("2");
								shopbusorderService.pay(shopbusorder2);
							}
						}
				}
			}
			res.put("orderId", shopbusorder.getId());
			res.put("amount", shopbusorder.getPrice());
			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 抢券
	 * @param req
	 * @return
	 */
	@PostMapping("/grabVoucher")
	@ResponseBody
	public ResJson grabVoucher(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败");
		try {
			if (isBlank(req.getUid(), req.getString("voucherId"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			if ("1".equals(member.getState())) {
				res.setResultNote("用户被冻结");
				return res;
			}
			ShopCoupon shopCoupon = shopCouponService.get(req.getString("voucherId"));
			if (shopCoupon == null || !"1".equals(shopCoupon.getState()) || !"1".equals(shopCoupon.getAudit())) {
				res.setResultNote("优惠券不存在或已下架");
				return res;
			}
			if (shopCoupon.getEndDate().before(new Date())) {
				res.setResultNote("优惠券已过期");
				return res;
			}

			CouponOrder couponOrder = new CouponOrder();
			couponOrder.setIsNewRecord(true);
			couponOrder.setId(OrderNumPrefix.couponOrder + IdGen.getOrderNo());
			couponOrder.setMember(member);
			couponOrder.setShop(shopCoupon.getShop());
			couponOrder.setCouponId(shopCoupon.getId());
			couponOrder.setCode(shopCoupon.getCode());
			couponOrder.setPrice(shopCoupon.getPrice());
			couponOrder.setMoney(shopCoupon.getMoney());
			couponOrder.setStartDate(shopCoupon.getStartDate());
			couponOrder.setEndDate(shopCoupon.getEndDate());
			couponOrder.setPoint(shopCoupon.getPoint());
			couponOrder.setState("0");
			couponOrder.setAmount(shopCoupon.getAmount());
			couponOrderService.save(couponOrder);

			res.put("orderId", couponOrder.getId());
			res.put("amount", couponOrder.getPrice());
			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 文案列表
	 * @param req
	 * @return
	 */
	@PostMapping("/copywritingList")
	@ResponseBody
	public ResJson copywritingList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");

		try {
			Map<String, String> params = Maps.newHashMap();
			params.put("min_id", StringUtils.isNotBlank(req.getString("min_id")) ? req.getString("min_id") : "1");
			params.put("page_size", req.getPageSize() + "");
			JSONObject jsonObject = DingdanxiaUtils.dingdanxiaAPI(DingdanxiaUtils.goodcopy, params);
			logger.debug("订单返回数据：" + jsonObject.toString());
			if (!"200".equals(jsonObject.getString("code"))) {
				res.setResultNote(jsonObject.getString("msg"));
				return res;
			}
			res.put("min_id", jsonObject.getString("min_id"));
			JSONObject dataObject = jsonObject.getJSONObject("data");
			if (dataObject != null) {
				JSONArray dataArray = dataObject.getJSONArray("data");
				if (dataArray != null) {
					res.setDataList(dataArray);
				}
			}

			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 支付
	 * @param req
	 * @return
	 */
	@PostMapping("/wxPay")
	@ResponseBody
	public ResJson wxPay(@RequestBody ReqJson req, HttpServletRequest request) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		BigDecimal amount = BigDecimal.ZERO;// 支付金额
		String title = "订单支付";
		Member Member = null;
		try {
			String orderId = req.getString("orderId");
			if (StringUtils.isBlank(orderId)) {
				res.setResultNote("订单号不能为空");
				return res;
			}
			//微信公众号支付
			if ("3".equals(req.getString("type"))&&StringUtils.isBlank(req.getString("code"))) {
				res.setResultNote("code不能为空");
				return res;
			}
			if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.chongzhi)) {// 充值订单
				RechargeOrder order = rechargeOrderService.get(orderId);
				if (order != null && "0".equals(order.getState())) {
					title = "话费充值";
					amount = new BigDecimal(order.getPrice());
					Member=order.getMember();
					Member=memberService.get(Member.getId());
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.totalId)) {// 云店商品大订单
				ProductOrder productOrder = new ProductOrder();
				productOrder.setTotalId(orderId);
				List<ProductOrder> list = productOrderService.findList(productOrder);
				Double point = 0.00;
				String isdaimai ="0";//0不是代买 1是代买
				if (!list.isEmpty()) {
					title = "云店商品订单";
					for (ProductOrder order : list) {
						if ("0".equals(order.getState())) {
							amount = amount.add(new BigDecimal(order.getAmount()));
							Member=order.getMember();
							Member=memberService.get(Member.getId());
							if(order.getDaimai()!=null){
								Member=memberService.get(order.getDaimai());
							}
						}
						point += Double.valueOf(order.getPoint());
						if(order.getDaimai()!=null){
							isdaimai ="1";
						}
					}
					res.put("point",point);
					res.put("isdaimai",isdaimai);
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.groupOrder)) {// 拼团订单
				GroupOrder groupOrder = groupOrderService.get(orderId);
				Double point = 0.00;
				String isdaimai ="0";//0不是代买 1是代买
				if (groupOrder != null && "0".equals(groupOrder.getState())) {
					title = "拼团商品订单";
					amount = new BigDecimal(groupOrder.getAmount());
					Member=groupOrder.getMember();
					Member=memberService.get(Member.getId());
					if(groupOrder.getDaimai()!=null){
						Member=memberService.get(groupOrder.getDaimai());
					}
					if(groupOrder.getDaimai()!=null){
						isdaimai ="1";
					}
					point = Double.valueOf(groupOrder.getPoint());
					res.put("point",point);
					res.put("isdaimai",isdaimai);
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.shopOrder)) {// 实体商家入驻订单
				Shop shop = shopService.get(orderId);
				if (shop != null && "0".equals(shop.getAuditState())) {
					title = "实体商家入驻订单";
					amount = new BigDecimal(shop.getAmount());
					if("0".equals(shop.getXhtype())){
						amount = new BigDecimal(shop.getPaymoney());
					}

					Member=shop.getMember();
					Member=memberService.get(Member.getId());
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.storeOrder)) {// 厂家入驻订单
				Store store = storeService.get(orderId);
				if (store != null && "0".equals(store.getAuditState())) {
					title = "厂家入驻订单";
					amount = new BigDecimal(store.getAmount());
					if("0".equals(store.getXhtype())){
						amount = new BigDecimal(store.getPaymoney());
					}
					Member=store.getMember();
					Member=memberService.get(Member.getId());
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.proxyOrder)) {// 批发云店铺订单
				ProxyOrder proxyOrder = proxyOrderService.get(orderId);
				if (proxyOrder != null && "0".equals(proxyOrder.getState())) {
					title = "单品代理年服务费订单";
					amount = new BigDecimal(proxyOrder.getPrice());
					Member=proxyOrder.getMember();
					Member=memberService.get(Member.getId());
				}
			}else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.couponOrder)) {// 优惠券订单
				CouponOrder couponOrder = couponOrderService.get(orderId);
				if (couponOrder != null && "0".equals(couponOrder.getState())) {
					title = "商圈优惠券订单";
					amount = new BigDecimal(couponOrder.getPrice());
					Member=couponOrder.getMember();
					Member=memberService.get(Member.getId());
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.BusinessOrder)) {// 附近商圈订单
				ShopbusOrder shopbusorder =shopbusorderService.get(orderId);
				if (shopbusorder != null && "0".equals(shopbusorder.getState())) {
					title = "附近商圈订单";
					amount = new BigDecimal(shopbusorder.getPrice());
					Member=shopbusorder.getMember();
					Member=memberService.get(Member.getId());
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.proxyProductOrder)) {// 增选产品订单
				ProxyProduct proxyProduct = proxyProductService.get(orderId);
				if (proxyProduct != null && "0".equals(proxyProduct.getOrderState())) {
					title = "增选产品订单";
					amount = new BigDecimal(proxyProduct.getFee());
					Member=proxyProduct.getMember();
					Member=memberService.get(Member.getId());
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.llbt)) {// 流量补贴产品订单
				Llbt llbt = llbtService.getOrderno(orderId);
				if (llbt != null && "0".equals(llbt.getState())) {
					title = "流量补贴订单";
					amount = new BigDecimal(llbt.getMoney());
					Member=llbt.getMember();
					Member=memberService.get(Member.getId());
				}
			}else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.xhq)) {// 选货权订单
				Xhq xhq = xhqService.get(orderId);
				if (xhq != null && "0".equals(xhq.getState())) {
					title = "选货权订单";
					amount = new BigDecimal(xhq.getMoney());
					Member = xhq.getMember();
					Member = memberService.get(Member.getId());
				}
			}else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.gift)) {// 赠品支付订单
				Gift gift = giftService.get(orderId);
				if (gift != null && "0".equals(gift.getState())) {
					title = "赠品订单";
					amount = new BigDecimal(gift.getMoney());
					Member = gift.getMember();
					Member = memberService.get(Member.getId());
				}
			}
			else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.JP)) {// 奖品支付订单
				Prize prize = prizeService.get(orderId);
				if (prize != null && "0".equals(prize.getState())) {
					title = "奖品订单";
					amount = new BigDecimal(prize.getMoney());
					Member = prize.getMember();
					Member = memberService.get(Member.getId());
				}
			}else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.XFQ)) {// 消费券支付订单
				Xfq xfq = xfqService.get(orderId);
				if (xfq != null && "0".equals(xfq.getState())) {
					title = "消费券订单";
					amount = new BigDecimal(xfq.getMoney());
					Member = xfq.getMember();
					Member = memberService.get(Member.getId());
				}
			}else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.VIP)) {// VIP支付订单
				Vip vip = vipService.get(orderId);
				if (vip != null && "0".equals(vip.getState())) {
					title = "VIP订单";
					amount = new BigDecimal(vip.getMoney());
					Member = vip.getMember();
					Member = memberService.get(Member.getId());
				}
			}else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.CFM)) {// VIP支付订单
				Cfm cfm = cfmService.get(orderId);
				if (cfm != null && "0".equals(cfm.getState())) {
					title = "云店铺订单";
					amount = new BigDecimal(cfm.getMoney());
					Member = cfm.getMember();
					Member = memberService.get(Member.getId());
				}
			}
			else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.HKQY)) {// 惠康区域支付订单
				Hkqy hkqy = hkqyService.get(orderId);
				if (hkqy != null && "0".equals(hkqy.getState())) {
					title = "惠康区域代理订单";
					amount = new BigDecimal(hkqy.getMoney());
					Member = hkqy.getMember();
					Member = memberService.get(Member.getId());
				}
			}
			else {// 云店商品订单
				ProductOrder order = productOrderService.get(orderId);
				if (order != null && "0".equals(order.getState())) {
					title = "云店商品订单";
					amount = new BigDecimal(order.getAmount());
					Member=order.getMember();
					Member=memberService.get(Member.getId());
					if(order.getDaimai()!=null){
						Member=memberService.get(order.getDaimai());
					}
					String isdaimai ="0";
					if(order.getDaimai()!=null){
						isdaimai ="1";
					}
					res.put("isdaimai",isdaimai);
					res.put("point", order.getPoint());
				}
			}

			if (amount.compareTo(BigDecimal.ZERO) > 0) {
				if ("1".equals(req.getString("category"))) {
					String body = "";
					if ("2".equals(req.getString("type")) || "3".equals(req.getString("type"))) {
						body = AlipayUtils.createOrder(title, title, amount.toString(), orderId, AlipayUtils.h5, req.getString("returnUrl"));
					} else {
						body = AlipayUtils.createOrder(title, title, amount.toString(), orderId, AlipayUtils.app);
					}
					res.put("body", body);
				} else {
					orderId = orderId;// 微信支付不同场景需要不同的订单号
//					orderId = orderId + RandomUtil.randomNumberFixLength(4);// 微信支付不同场景需要不同的订单号
					String openid="";
					openid=Member.getOpenid();//获取openid
					if("4".equals(req.getString("type"))){
						openid=Member.getWxAppOpenid();//获取小程序openid
					}
					if(StringUtils.isBlank(openid)){//判断openid是否为空
						if( "3".equals(req.getString("type"))){
							String appid="wxfd00b75fa13f1b76";
							String AppSecret="44838dd42a856513397bd1322f0d7641";
							String code=req.getString("code");
							WxpubOAuth.OAuthResult OAuthResult=WxpubOAuth.getOpenId(appid,AppSecret,code);
							openid=(String)OAuthResult.getOpenid();
							if(StringUtils.isBlank(openid)){
								res.setResultNote("code过期，请刷新重试！");
								return  res;
							}
							Member.setOpenid(openid);
							memberService.save(Member);//更新openid
						}else if("4".equals(req.getString("type"))){
							res.setResultNote("openid不存在请重新授权登陆！");
							return  res;
						}
					}
					Map<String, String> body = WxPayUtils.createOrder("1".equals(req.getString("type")) ? WxPayUtils.TRADE_TYPE_APP :"2".equals(req.getString("type"))? WxPayUtils.TRADE_TYPE_MWEB:"3".equals(req.getString("type"))?WxPayUtils.TRADE_TYPE_JSAPI:"4".equals(req.getString("type"))?WxPayUtils.TRADE_TYPE_WXAPPJSAPI:WxPayUtils.TRADE_TYPE_APP, openid, title, orderId, amount.toString(), IPUtil.getRemoteAddress(request));
					res.put("body", body);
				}
				res.setResult("0");
				res.setResultNote("获取成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 *获取用户信息
	 * */
	@PostMapping("/getOauthUserInfo")
	@ResponseBody
	public String getOpenid(@RequestBody ReqJson req) {
		String appid="wxfd00b75fa13f1b76";
		String AppSecret="44838dd42a856513397bd1322f0d7641";
		String code=req.getString("code");
		String openid="";
		try {
			WxpubOAuth.OAuthResult OAuthResult=WxpubOAuth.getOpenId(appid,AppSecret,code);
			openid=OAuthResult.getOpenid();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.debug(e.getMessage());
		}
		return openid;
	}
	/**
	 * 我惠卡支付
	 * @param req
	 * @return
	 */
	@PostMapping("/wohuiPay")
	@ResponseBody
	public ResJson wohuiPay(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("支付失败");
		BigDecimal amount = BigDecimal.ZERO;// 支付金额
		String title = "订单支付";
		try {
			String orderId = req.getString("orderId");
			if (StringUtils.isBlank(orderId)) {
				res.setResultNote("订单号不能为空");
				return res;
			}
			if (StringUtils.isBlank(req.getString("type"))) {
				res.setResultNote("请选择支付类型");
				return res;
			}
			if (StringUtils.isBlank(req.getString("payPwd"))) {
				res.setResultNote("请输入支付密码");
				return res;
			}
			String uid = ""; // 用户ID

			RechargeOrder rechargeOrder = null;
			GroupOrder groupOrder = null;
			Shop shop = null;
			Store store = null;
			ProxyOrder proxyOrder = null;
			CouponOrder couponOrder = null;
			ProductOrder productOrder = null;
			List<ProductOrder> productOrderList = null;
			ProxyProduct proxyProduct = null;
			Llbt llbt = null;
			Xhq xhq = null;
			Gift gift = null;
			Ktq ktq = null;
			Prize prize = null;
			Xfq xfq = null;
			Vip vip = null;
			Cfm cfm = null;
			Hkqy hkqy = null;
			ShopbusOrder shopbusorder = null;

			if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.chongzhi)) {// 充值订单
				rechargeOrder = rechargeOrderService.get(orderId);
				if (rechargeOrder != null && "0".equals(rechargeOrder.getState())) {
					title = "话费充值";
					amount = new BigDecimal(rechargeOrder.getPrice());
					uid = rechargeOrder.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.totalId)) {// 云店商品大订单
				ProductOrder po = new ProductOrder();
				po.setTotalId(orderId);
				productOrderList = productOrderService.findList(po);
				if (!productOrderList.isEmpty()) {
					title = "云店商品订单";
					Double point = 0.00;
					String isdaimai ="0";
					for (ProductOrder order : productOrderList) {
						if ("0".equals(order.getState())) {
							amount = amount.add(new BigDecimal(order.getAmount()));
							if (order.getDaimai() != null && StringUtils.isNotBlank(order.getDaimai().getId())) {
								uid = order.getDaimai().getId();
							} else {
								uid = order.getMember().getId();
							}
						}
						point += Double.valueOf(order.getPoint());
						if(order.getDaimai()!=null){
							isdaimai ="1";
						}
					}
					res.put("point",point);
					res.put("isdaimai",isdaimai);
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.groupOrder)) {// 拼团订单
                groupOrder = groupOrderService.get(orderId);
                Double point = 0.00;
                String isdaimai ="0";
                if (groupOrder != null && "0".equals(groupOrder.getState())) {
                    title = "拼团商品订单";
                    amount = new BigDecimal(groupOrder.getAmount());
                    if (groupOrder.getDaimai() != null && StringUtils.isNotBlank(groupOrder.getDaimai().getId())) {
                        uid = groupOrder.getDaimai().getId();
                        isdaimai ="1";
                    } else {
                        uid = groupOrder.getMember().getId();
                    }
                    point = Double.valueOf(groupOrder.getPoint());
                    res.put("point",point);
                    res.put("isdaimai",isdaimai);
                }
            } else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.shopOrder)) {// 实体商家入驻订单
				shop = shopService.get(orderId);
				if (shop != null && "0".equals(shop.getAuditState())) {
					title = "实体商家入驻订单";
					amount = new BigDecimal(shop.getAmount());
					if("0".equals(shop.getXhtype())){
						amount = new BigDecimal(shop.getPaymoney());
					}
					uid = shop.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.storeOrder)) {// 厂家入驻订单
				store = storeService.get(orderId);
				if (store != null && "0".equals(store.getAuditState())) {
					title = "厂家入驻订单";
					amount = new BigDecimal(store.getAmount());
					if("0".equals(store.getXhtype())){
						amount = new BigDecimal(store.getPaymoney());
					}
					uid = store.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.proxyOrder)) {// 批发云店铺订单
				proxyOrder = proxyOrderService.get(orderId);
				if (proxyOrder != null && "0".equals(proxyOrder.getState())) {
					title = "单品代理年服务费订单";
					amount = new BigDecimal(proxyOrder.getPrice());
					uid = proxyOrder.getMember().getId();
				}
			}  else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.couponOrder)) {// 优惠券订单
				couponOrder = couponOrderService.get(orderId);
				if (couponOrder != null && "0".equals(couponOrder.getState())) {
					title = "商圈优惠券订单";
					amount = new BigDecimal(couponOrder.getPrice());
					uid = couponOrder.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.BusinessOrder)) {// 附近商圈订单
				 shopbusorder =shopbusorderService.get(orderId);
				if (shopbusorder != null && "0".equals(shopbusorder.getState())) {
					title = "附近商圈订单";
					amount = new BigDecimal(shopbusorder.getPrice());
					uid = shopbusorder.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.proxyProductOrder)) {// 增选产品订单
				proxyProduct = proxyProductService.get(orderId);
				if (proxyProduct != null && "0".equals(proxyProduct.getOrderState())) {
					title = "增选产品订单";
					amount = new BigDecimal(proxyProduct.getFee());
					//ProxyOrder order = proxyOrderService.get(proxyProduct.getProxyId());
					//uid = order.getMember().getId();
					uid = proxyProduct.getMember().getId();
				}
			}else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.llbt)) {// 增选产品订单
				llbt= llbtService.getOrderno(orderId);
				if (llbt != null && "0".equals(llbt.getState())) {
					title = "流量补贴订单";
					amount = new BigDecimal(llbt.getMoney());
					uid = llbt.getMember().getId();
				}
			}else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.xhq)) {// 增选产品订单
				xhq = xhqService.get(orderId);
				if (xhq != null && "0".equals(xhq.getState())) {
					title = "选货权订单";
					amount = new BigDecimal(xhq.getMoney());
					uid = xhq.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.gift)) {// 赠品订单
				gift  = giftService.get(orderId);
				if (gift != null && "0".equals(gift.getState())) {
					title = "赠品订单";
					amount = new BigDecimal(gift.getMoney());
					uid = gift.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.KTQ)) {// 开通权订单
				ktq  = ktqService.get(orderId);
				if (ktq != null && "0".equals(ktq.getState())) {
					title = "开通权订单";
					amount = new BigDecimal(ktq.getMoney());
					uid = ktq.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.JP)) {// 奖品订单
				prize  = prizeService.get(orderId);
				if (prize != null && "0".equals(prize.getState())) {
					title = "奖品订单";
					amount = new BigDecimal(prize.getMoney());
					uid = prize.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.XFQ)) {// 消费券订单
				xfq  = xfqService.get(orderId);
				if (xfq != null && "0".equals(xfq.getState())) {
					title = "消费券订单";
					amount = new BigDecimal(xfq.getMoney());
					uid = xfq.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.VIP)) {// 订单
				vip  = vipService.get(orderId);
				if (vip != null && "0".equals(vip.getState())) {
					title = "VIP订单";
					amount = new BigDecimal(vip.getMoney());
					uid = vip.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.CFM)) {// 订单
				cfm  = cfmService.get(orderId);
				if (cfm != null && "0".equals(cfm.getState())) {
					title = "云店铺订单";
					amount = new BigDecimal(cfm.getMoney());
					uid = cfm.getMember().getId();
				}
			} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.HKQY)) {// 惠康区域代理订单
				hkqy  = hkqyService.get(orderId);
				if (hkqy != null && "0".equals(hkqy.getState())) {
					title = "惠康区域代理订单";
					amount = new BigDecimal(hkqy.getMoney());
					uid = hkqy.getMember().getId();
				}
			}
			else {// 云店商品订单
				productOrder = productOrderService.get(orderId);
				if (productOrder != null && "0".equals(productOrder.getState())) {
					title = "云店商品订单";
					String isdaimai ="0";
					amount = new BigDecimal(productOrder.getAmount());
					if (productOrder.getDaimai() != null && StringUtils.isNotBlank(productOrder.getDaimai().getId())) {
						uid = productOrder.getDaimai().getId();
					} else {
						uid = productOrder.getMember().getId();
					}
					res.put("point",productOrder.getPoint());
					if(productOrder.getDaimai()!=null){
						isdaimai ="1";
					}
					res.put("isdaimai",isdaimai);
				}
			}

			if (amount.compareTo(BigDecimal.ZERO) >= 0 && StringUtils.isNotBlank(uid)) {
				// 调用三方会员系统支付
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("CardGUID", uid));
				list.add(new WohuiEntity("PayPwd", req.getString("payPwd")));
				list.add(new WohuiEntity("OrderNO", orderId));
				list.add(new WohuiEntity("Money", amount.toString()));
				list.add(new WohuiEntity("PayMent", "3".equals(req.getString("type")) ? "XFJJPAY" : "XFBPAY"));
				list.add(new WohuiEntity("Remark", title));
				list.add(new WohuiEntity("Source", "YD"));
				JSONObject jsonObject = WohuiUtils.send(WohuiUtils.WHKPay, list);
				if (!"0000".equals(jsonObject.getString("respCode"))) {
					res.setResultNote(jsonObject.getString("respMsg"));
					return res;
				}
				if (rechargeOrder != null) {
					// 暂不处理
				} else if (groupOrder != null) {
					groupOrder.setState("1");
					groupOrder.setPayType(req.getString("type"));
					groupOrder.setPayDate(new Date());
					groupOrder.setPayNo(orderId);
					groupOrderService.pay(groupOrder);
				} else if (shop != null) {
					shop.setAuditState("1");
					shop.setPayType(req.getString("type"));
					shop.setOrderNo(orderId);
					shopService.pay(shop);
				} else if (store != null) {
					store.setAuditState("1");
					store.setPayType(req.getString("type"));
					store.setOrderNo(orderId);
					storeService.pay(store);
				} else if (proxyOrder != null) {
					proxyOrder.setState("1");
					proxyOrder.setPayDate(new Date());
					proxyOrder.setPayType(req.getString("type"));
					proxyOrder.setOrderNo(orderId);
					proxyOrderService.pay(proxyOrder);
				} else if (couponOrder != null) {
					couponOrder.setPayType(req.getString("type"));
					couponOrder.setPayDate(new Date());
					couponOrder.setPayNo(orderId);
					couponOrder.setState("1");
					couponOrderService.pay(couponOrder);
				} else if (shopbusorder != null) { //附近商家订单
					shopbusorder.setPayType(req.getString("type"));
					shopbusorder.setPayDate(new Date());
					shopbusorder.setPayNo(orderId);
					shopbusorder.setState("2");
					shopbusorderService.pay(shopbusorder);
				} else if (productOrder != null) {
					productOrder.setState("1");
					productOrder.setPayNo(orderId);
					productOrder.setPayType(req.getString("type"));
					productOrder.setPayDate(new Date());
					productOrderService.pay(productOrder);
				} else if (productOrderList != null && !productOrderList.isEmpty()) {
					productOrderService.pay(productOrderList, orderId, req.getString("type"),"");
				} else if (proxyProduct != null) {
					proxyProduct.setOrderState("1");
					proxyProduct.setPayDate(new Date());
					proxyProduct.setPayNo(orderId);
					proxyProduct.setPayType(req.getString("type"));
					proxyProductService.pay(proxyProduct);
				}else if (llbt != null) {
					llbt.setState("1");
					llbt.setPayDate(new Date());
					llbt.setFinishdate(new Date());
					llbtService.pay(llbt);
				}else if (xhq != null) {
					xhq.setState("1");
					xhq.setPayDate(new Date());
					xhq.setFinishdate(new Date());
					xhqService.pay(xhq);
				}else if (gift != null) {
					gift.setState("1");
					gift.setPayType(req.getString("type"));
					gift.setPayDate(new Date());
					gift.setFinishdate(new Date());
					giftService.pay(gift);
				}else if (prize != null) {
					prize.setState("1");
					prize.setPayType(req.getString("type"));
					prize.setPayDate(new Date());
					prize.setFinishdate(new Date());
					prizeService.pay(prize);
				}else if (xfq != null) {
					xfq.setState("1");
					xfq.setPayType(req.getString("type"));
					xfq.setPayDate(new Date());
					xfq.setFinishdate(new Date());
					xfqService.pay(xfq);
				}else if (vip != null) {
					vip.setState("1");
					vip.setPayType(req.getString("type"));
					vip.setPayDate(new Date());
					vip.setFinishdate(new Date());
					vipService.pay(vip);
				}else if (cfm != null) {
					cfm.setState("1");
					cfm.setPayType(req.getString("type"));
					cfm.setPayDate(new Date());
					cfm.setFinishdate(new Date());
					cfmService.pay(cfm);
				}else if (hkqy != null) {
					hkqy.setState("1");
					hkqy.setPayType(req.getString("type"));
					hkqy.setPayDate(new Date());
					hkqy.setFinishdate(new Date());
					hkqyService.pay(hkqy);
				}
				else if (ktq != null) {
					ktq.setState("1");
					ktq.setPayType(req.getString("type"));
					ktq.setPayDate(new Date());
					ktq.setFinishdate(new Date());
					ktqService.pay(ktq);
				}


				res.setResult("0");
				res.setResultNote("支付成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * H5支付
	 * @param req
	 * @return
	 */
	@PostMapping("/h5Pay")
	public void h5Pay(@RequestBody ReqJson req, HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html;charset=" + AlipayUtils.CHARSET);
		BigDecimal amount = BigDecimal.ZERO;// 支付金额
		String title = "订单支付";
		try {
			String orderId = req.getString("orderId");
			if (StringUtils.isNotBlank(orderId)) {
				if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.chongzhi)) {// 充值订单
					RechargeOrder order = rechargeOrderService.get(orderId);
					if (order != null && "0".equals(order.getState())) {
						title = "话费充值";
						amount = new BigDecimal(order.getPrice());
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.totalId)) {// 云店商品大订单
					ProductOrder productOrder = new ProductOrder();
					productOrder.setTotalId(orderId);
					List<ProductOrder> list = productOrderService.findList(productOrder);
					if (!list.isEmpty()) {
						title = "云店商品订单";
						for (ProductOrder order : list) {
							if ("0".equals(order.getState())) {
								amount = amount.add(new BigDecimal(order.getAmount()));
							}
						}
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.groupOrder)) {// 拼团订单
					GroupOrder groupOrder = groupOrderService.get(orderId);
					if (groupOrder != null && "0".equals(groupOrder.getState())) {
						title = "拼团商品订单";
						amount = new BigDecimal(groupOrder.getAmount());
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.shopOrder)) {// 实体商家入驻订单
					Shop shop = shopService.get(orderId);
					if (shop != null && "0".equals(shop.getAuditState())) {
						title = "实体商家入驻订单";
						amount = new BigDecimal(shop.getAmount());
						if("0".equals(shop.getXhtype())){
							amount = new BigDecimal(shop.getPaymoney());
						}

					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.storeOrder)) {// 厂家入驻订单
					Store store = storeService.get(orderId);
					if (store != null && "0".equals(store.getAuditState())) {
						title = "厂家入驻订单";
						amount = new BigDecimal(store.getAmount());
						if("0".equals(store.getXhtype())){
							amount = new BigDecimal(store.getPaymoney());
						}
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.proxyOrder)) {// 单品代理订单
					ProxyOrder proxyOrder = proxyOrderService.get(orderId);
					if (proxyOrder != null && "0".equals(proxyOrder.getState())) {
						title = "单品代理订单";
						amount = new BigDecimal(proxyOrder.getPrice());
					}
				} else {// 云店商品订单
					ProductOrder order = productOrderService.get(orderId);
					if (order != null && "0".equals(order.getState())) {
						title = "云店商品订单";
						amount = new BigDecimal(order.getAmount());
					}
				}

				if (amount.compareTo(BigDecimal.ZERO) > 0) {
					String body = AlipayUtils.createOrder(title, title, amount.toString(), orderId, AlipayUtils.h5);
					response.getWriter().write(body);//直接将完整的表单html输出到页面
					response.getWriter().flush();
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			try {
				response.getWriter().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 删除单条消息
	 * @param req
	 * @return
	 */
	@PostMapping("/delMessage")
	@ResponseBody
	public ResJson delMessage(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("删除失败");
		try {
			if (StringUtils.isBlank(req.getString("msgId"))) {
				res.setResultNote("消息ID不能为空");
				return res;
			}

			msgService.delete(new Msg(req.getString("msgId")));
			res.setResult("0");
			res.setResultNote("删除成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 消息列表
	 * @param req
	 * @return
	 */
	@PostMapping("/messageaList")
	@ResponseBody
	public ResJson messageaList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}

			Msg msg = new Msg();
			msg.setMember(new Member(req.getUid()));
			Page<Msg> page = msgService.findPage(new Page<>(req.getPageNo(), req.getPageSize()), msg);
			res.setTotalPage(page.getTotalPage());
			for (Msg m : page.getList()) {
				Map<String, String> map = Maps.newHashMap();
				map.put("id", m.getId());
				map.put("title", m.getTitle());
				map.put("content", m.getContent());
				//map.put("contentUrl", );
				//map.put("orderId", );
				map.put("status", m.getState());
				map.put("adtime", DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(m.getCreateDate()));
				dataList.add(map);
			}
			// 修改为已读
			msgService.executeUpdateSql("UPDATE t_msg SET state = '1' WHERE uid = '"+req.getUid()+"' AND state = '0'");
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 云店商品评论列表
	 * @param req
	 * @return
	 */
	@PostMapping("/commentList")
	@ResponseBody
	public ResJson commentList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("productId"))) {
				res.setResultNote("商品ID不能为空");
				return res;
			}

			Comment comment = new Comment();
			comment.setProduct(new Product(req.getString("productId")));
			Page<Comment> page = commentService.findPage(new Page<>(req.getPageNo(), req.getPageSize()), comment);
			res.setTotalPage(page.getTotalPage());
			res.setTotalCount(page.getCount());
			for (Comment c : page.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("userIcon", getRealImage(c.getMember().getIcon()));
				map.put("nickName", c.getMember().getNickname());
				map.put("score", c.getScore());
				map.put("adtime", DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(c.getCreateDate()));
				map.put("content", c.getContent());
				map.put("reply", c.getState());
				map.put("replyContent", c.getReply());
				map.put("replyDate", c.getReplyDate() != null ? DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(c.getReplyDate()) : "");
				List<String> images = Lists.newArrayList();
				if (StringUtils.isNotBlank(c.getImages())) {
					String[] imgs = c.getImages().split("\\|");
					for (String img : imgs) {
						String realImage = getRealImage(img);
						if (StringUtils.isNotBlank(realImage)) {
							images.add(realImage);
						}
					}
				}
				map.put("images", images);
				dataList.add(map);
			}

			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 根据商家ID查询商家代金券列表
	 * @param req
	 * @return
	 */
	@PostMapping("/findVoucherListByshopId")
	@ResponseBody
	public ResJson findVoucherListByshopId(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		List<String> images = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("shopId"))) {
				res.setResultNote("商家ID不能为空");
				return res;
			}

			Shop shop = shopService.get(req.getString("shopId"));
			if (shop == null) {
				res.setResultNote("店铺不存在");
				return res;
			}
			res.put("shopName", shop.getTitle());
			res.put("lon", shop.getLon());
			res.put("lat", shop.getLat());
			res.put("address", shop.getAddress());
			res.put("logo", getRealImage(shop.getIcon()));

			String introduction = "";
			if ("1".equals(shop.getShowState())) {
				introduction = shop.getContent();
				if (StringUtils.isNotBlank(shop.getImages())) {
					for (String image : shop.getImages().split("\\|")) {
						if (StringUtils.isNotBlank(image)) {
							images.add(getRealImage(image));
						}
					}
				}
			}
			res.put("introduction", introduction);
			res.put("images", images);

			ShopCoupon shopCoupon = new ShopCoupon();
			shopCoupon.setShop(shop);
			shopCoupon.setState("1");
			shopCoupon.setAudit("1");
			shopCoupon.setDataScope(" AND a.end_date>NOW() ");
			Page<ShopCoupon> page = shopCouponService.findPage(new Page<>(req.getPageNo(), req.getPageSize()), shopCoupon);
			res.setTotalPage(page.getTotalPage());
			for (ShopCoupon coupon : page.getList()) {
				Map<String, String> map = Maps.newHashMap();
				map.put("voucherId", coupon.getId());
				map.put("reachMoney", coupon.getMoney());
				map.put("price", coupon.getPrice());
				map.put("integral", coupon.getPoint());
				map.put("startTime", DateFormatUtil.ISO_ON_DATE_FORMAT.format(coupon.getStartDate()));
				map.put("endTime", DateFormatUtil.ISO_ON_DATE_FORMAT.format(coupon.getEndDate()));
				map.put("content", coupon.getContent());
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 附近商圈地图商家列表
	 * @param req
	 * @return
	 */
	@PostMapping("/mapShopList")
	@ResponseBody
	public ResJson mapShopList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (isBlank(req.getString("lon"), req.getString("lat"))) {
				res.setResultNote("请选择坐标位置");
				return res;
			}
			Shop shop = new Shop();
			//shop.setLon(req.getDouble("lon"));
			//shop.setLat(req.getDouble("lat"));
			shop.setState("0");
			shop.setAuditState("2");
			shop.setDataScope(" AND ROUND(6378.138*2*ASIN(SQRT(POW(SIN(("+req.getDoubleValue("lat")+"*PI()/180-a.lat*PI()/180)/2),2)+COS("+req.getDoubleValue("lat")+"*PI()/180)*COS(a.lat*PI()/180)*POW(SIN(("+req.getDoubleValue("lon")+"*PI()/180-a.lon*PI()/180)/2),2)))*1000)<20000 ");
			List<Shop> list = shopService.findList(shop);
			for (Shop s : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("shopId", s.getId());
				map.put("shopName", s.getTitle());
				map.put("shopLogo", getRealImage(s.getIcon()));
				map.put("shopAddr", s.getAddress());
				map.put("lon", s.getLon());
				map.put("lat", s.getLat());
				dataList.add(map);
			}

			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 最热搜索关键词列表
	 * @param req
	 * @return
	 */
	@PostMapping("/keywordList")
	@ResponseBody
	public ResJson keywordList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<String> keywords = Lists.newArrayList();
		try {
			List<Keyword> list = keywordService.findList(new Keyword());
			for (Keyword keyword : list) {
				keywords.add(keyword.getTitle());
			}
			res.put("keywords", keywords);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 加入购物车
	 * @param req
	 * @return
	 */
	@PostMapping("/addCart")
	@ResponseBody
	public ResJson addCart(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("添加失败");
		try {
			if (isBlank(req.getUid(), req.getString("ggId"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			// 判断规格是否存在
			ProductSku productSku = productSkuService.get(req.getString("ggId"));
			if (productSku == null) {
				res.setResultNote("该规格不存在");
				return res;
			}
			if (productSku.getProduct() == null || "1".equals(productSku.getProduct().getState()) || !"1".equals(productSku.getProduct().getAuditState())) {
				res.setResultNote("该商品不存在或已下架");
				return res;
			}
			int count = req.getIntValue("count") > 0 ? req.getIntValue("count") : 1;
			// 查询购物车
			Cart cart = new Cart();
			cart.setMember(new Member(req.getUid()));
			cart.setSku(productSku);
			List<Cart> list = cartService.findList(cart);
			if (list.isEmpty()) {
				cart.setStore(productSku.getProduct().getStore());
				cart.setProduct(productSku.getProduct());
				cart.setQty(count);
			} else {
				cart = list.get(0);
				cart.setQty(cart.getQty() + count);
			}
			cartService.save(cart);
			res.setResult("0");
			res.setResultNote("添加成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 收藏或取消收藏商家
	 * @param req
	 * @return
	 */
	@PostMapping("/collectionOrCancelShop")
	@ResponseBody
	public ResJson collectionOrCancelShop(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败");
		try {
			if (isBlank(req.getUid(), req.getString("shopId"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			CollectStore collectStore = new CollectStore();
			collectStore.setMember(new Member(req.getUid()));
			collectStore.setStore(new Store(req.getString("shopId")));
			List<CollectStore> list = collectStoreService.findList(collectStore);
			if (list.isEmpty()) {
				collectStoreService.save(collectStore);
				res.put("type", "0");
			} else {
				collectStoreService.deleteAll(list);
				res.put("type", "1");
			}
			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 充值记录
	 * @param req
	 * @return
	 */
	@PostMapping("/rechargeRecordList")
	@ResponseBody
	public ResJson rechargeRecordList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getUid())) {
				res.setResultNote("请先登录");
				return res;
			}

			RechargeOrder rechargeOrder = new RechargeOrder();
			rechargeOrder.setMember(new Member(req.getUid()));
			rechargeOrder.setDataScope(" AND a.state != '0' ");
			Page<RechargeOrder> page = rechargeOrderService.findPage(new Page<RechargeOrder>(req.getPageNo(), req.getPageSize()), rechargeOrder);
			res.setTotalPage(page.getTotalPage());
			for (RechargeOrder order : page.getList()) {
				Map<String, String> map = Maps.newHashMap();
				map.put("title", order.getPhone());
				map.put("money", order.getAmount());
				map.put("integral", order.getPoint());
				map.put("adtime", DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(order.getCreateDate()));
				dataList.add(map);
			}

			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 充值话费
	 * @param req
	 * @return
	 */
	@PostMapping("/rechargeTele")
	@ResponseBody
	public ResJson rechargeTele(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("提交失败");
		try {
			if (isBlank(req.getUid(), req.getString("telephone"), req.getString("packageId"))) {
				res.setResultNote("数据不完整");
				return res;
			}
			// 检测手机号
			if (!PhoneUtils.isMobile(req.getString("telephone"))) {
				res.setResultNote("手机号格式错误");
				return res;
			}
			String ispCode = PhoneUtils.getIspCode(req.getString("telephone"));
			if (StringUtils.isBlank(ispCode)) {
				res.setResultNote("暂不支持该号码充值");
				return res;
			}
			Member member = memberService.get(req.getUid());
			if (member == null) {
				res.setResultNote("用户不存在");
				return res;
			}
			Recharge recharge = rechargeService.get(req.getString("packageId"));
			if (recharge == null) {
				res.setResultNote("该套餐不存在");
				return res;
			}

			RechargeOrder rechargeOrder = new RechargeOrder();
			rechargeOrder.setIsNewRecord(true);
			rechargeOrder.setId(OrderNumPrefix.chongzhi + IdGen.getOrderNo());
			rechargeOrder.setMember(member);
			rechargeOrder.setIsp(ispCode);
			rechargeOrder.setPhone(req.getString("telephone"));
			rechargeOrder.setAmount(recharge.getAmount());
			rechargeOrder.setPrice(recharge.getPrice());
			rechargeOrder.setPoint(recharge.getPoint());
			rechargeOrder.setState("0");
			rechargeOrderService.save(rechargeOrder);

			res.put("orderId", rechargeOrder.getId());
			res.put("amount", rechargeOrder.getPrice());
			res.setResult("0");
			res.setResultNote("提交成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 充话费充值套餐列表
	 * @return
	 */
	@PostMapping("/rechargePackageList")
	@ResponseBody
	public ResJson rechargePackageList() {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			List<Recharge> list = rechargeService.findList(new Recharge());
			for (Recharge recharge : list) {
				Map<String, String> map = Maps.newHashMap();
				map.put("id", recharge.getId());
				map.put("reachMoney", recharge.getAmount());
				map.put("price", recharge.getPrice());
				map.put("integral", recharge.getPoint());
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 检测手机号是否注册
	 * @param req
	 * @return
	 */
	@PostMapping("/checkPhone")
	@ResponseBody
	public ResJson checkPhone(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		try {
			if (StringUtils.isBlank(req.getString("phone"))) {
				res.setResultNote("手机号不能为空");
				return res;
			}
			String state="0";
			List<WohuiEntity> entityList = Lists.newArrayList();
			entityList.add(new WohuiEntity("Phone", req.getString("phone")));
			JSONObject object = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, entityList);
			if ("0000".equals(object.getString("respCode"))) {
				state ="1";
				res.put("state",state);
				res.setResult("0");
				res.setResultNote("获取成功");
				return res;
			}
//			res.put("state", apiService.checkPhone(req.getString("phone")) ? "0" : "1");
			res.put("state", state);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 我惠出行
//	 * @param req
	 * @return
	 */
	@PostMapping("/travelInfo")
	@ResponseBody
	public ResJson travelInfo() {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> bannerList = Lists.newArrayList();
		List<Map<String, String>> categoryList = Lists.newArrayList();
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			// 轮播图
			Banner banner = new Banner();
			banner.setType("2");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				if (StringUtils.isNotBlank(b.getImage())) {
					Map<String, String> map = Maps.newHashMap();
					map.put("image", getRealImage(b.getImage()));
					map.put("category", b.getCategory());
					map.put("url", b.getUrl());
					map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
					map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
					map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
					map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
					map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
					bannerList.add(map);
				}
			}

			// 按钮图标
			Button button = new Button();
			//button.setDataScope(" AND a.type IN ('11','12','13','14','15')");
			button.setDataScope(" AND a.type IN ('11','12','13','15')");
			List<Button> list2 = buttonService.findList(button);
			for (Button b : list2) {
				Map<String, String> map = Maps.newHashMap();
				map.put("type", b.getType());
				map.put("icon", getRealImage(b.getIcon()));
				map.put("name", b.getTitle());
				categoryList.add(map);
			}

			res.put("bannerList", bannerList);
			res.put("categoryList", categoryList);
			res.put("dataList", dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 附近商圈列表
	 * @param req
	 * @return
	 */
	@PostMapping("/businessList")
	@ResponseBody
	public ResJson businessList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("请选择城市");
				return res;
			}

			ShopCoupon shopCoupon = new ShopCoupon();
			shopCoupon.setState("1");
			shopCoupon.setAudit("1");
			shopCoupon.setGroup("1");
			String dataScope = " AND  a.end_date > NOW() AND shop.state = '0' AND shop.audit_state = '2' AND shop.city='"+req.getString("city")+"' ";
			if (StringUtils.isNotBlank(req.getString("categoryId"))) {
				dataScope += " AND shop.category='"+req.getString("categoryId")+"' ";
			}
			shopCoupon.setDataScope(dataScope);
			Page<ShopCoupon> page = new Page<ShopCoupon>(req.getPageNo(), req.getPageSize());

			if ("1".equals(req.getString("sortType"))) {
				if (isBlank(req.getString("lon"), req.getString("lat"))) {
					res.setResultNote("请选择当前坐标");
					return res;
				}
				Shop shop = new Shop();
				shop.setLon(req.getDouble("lon"));
				shop.setLat(req.getDouble("lat"));
				shopCoupon.setShop(shop);
				page.setOrderBy("distance ASC");
			} else if ("2".equals(req.getString("sortType"))) {
				page.setOrderBy("a.price/a.money ASC");
			}

			Page<ShopCoupon> pageInfo = shopCouponService.findPage(page, shopCoupon);
			res.setTotalPage(pageInfo.getTotalPage());
			for (ShopCoupon coupon : pageInfo.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("shopId", coupon.getShop().getId());
				map.put("shopName", coupon.getShop().getTitle());
				map.put("shopLogo", getRealImage(coupon.getShop().getIcon()));
				map.put("shopAddr", coupon.getShop().getAddress());
				map.put("lon", coupon.getShop().getLon());
				map.put("lat", coupon.getShop().getLat());
				map.put("voucherId", coupon.getId());
				map.put("reachMoney", coupon.getMoney());
				map.put("price", coupon.getPrice());
				map.put("integral", coupon.getPoint());
				map.put("startTime", DateFormatUtil.ISO_ON_DATE_FORMAT.format(coupon.getStartDate()));
				map.put("endTime", DateFormatUtil.ISO_ON_DATE_FORMAT.format(coupon.getEndDate()));
				map.put("content", coupon.getContent());
				String introduction = "";
				List<String> images = Lists.newArrayList();
				if ("1".equals(coupon.getShop().getShowState())) {
					introduction = coupon.getShop().getContent();
					if (StringUtils.isNotBlank(coupon.getShop().getImages())) {
						for (String image : coupon.getShop().getImages().split("\\|")) {
							if (StringUtils.isNotBlank(image)) {
								images.add(getRealImage(image));
							}
						}
					}
				}
				map.put("introduction", introduction);
				map.put("images", images);
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 附近商圈单商家显示列表
	 * @param req
	 * @return
	 */
	@PostMapping("/businessShopList")
	@ResponseBody
	public ResJson businessShopList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, Object>> dataList = Lists.newArrayList();
		try {
			if (StringUtils.isBlank(req.getString("city"))) {
				res.setResultNote("请选择城市");
				return res;
			}
			Shop shop = new Shop();
			String dataScope = "AND a.state = '0' AND a.audit_state = '2' AND a.city='"+req.getString("city")+"' ";
			if (StringUtils.isNotBlank(req.getString("categoryId"))) {
				dataScope += " AND a.category='"+req.getString("categoryId")+"' ";
			}
			Page<Shop> page = new Page<Shop>(req.getPageNo(), req.getPageSize());
			shop.setDataScope(dataScope);
			if ("1".equals(req.getString("sortType"))) {
				if (isBlank(req.getString("lon"), req.getString("lat"))) {
					res.setResultNote("请选择当前坐标");
					return res;
				}
				shop.setLon(req.getDouble("lon"));
				shop.setLat(req.getDouble("lat"));
				page.setOrderBy("distance ASC");
			}
			Page<Shop> pageInfo = shopService.findPage(page, shop);
			res.setTotalPage(pageInfo.getTotalPage());
			for (Shop data : pageInfo.getList()) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("shopId", data.getId());
				map.put("shopName", data.getTitle());
				map.put("shopLogo", getRealImage(data.getIcon()));
				map.put("shopAddr", data.getAddress());
				map.put("lon", data.getLon());
				map.put("lat", data.getLat());
                map.put("hyrebate", new BigDecimal(10).multiply(new BigDecimal(1).subtract(new BigDecimal(data.getHyrebate()))).stripTrailingZeros().toPlainString());
						String point = new BigDecimal(100).multiply(new BigDecimal(data.getPtrebate())).stripTrailingZeros().toPlainString();
				map.put("yuanpoint", new BigDecimal("0.4").multiply(new BigDecimal(point)).setScale(1, BigDecimal.ROUND_DOWN).toPlainString());
				String introduction = "";
				List<String> images = Lists.newArrayList();
				if ("1".equals(data.getShowState())) {
					introduction = data.getContent();
					if (StringUtils.isNotBlank(data.getImages())) {
						for (String image : data.getImages().split("\\|")) {
							if (StringUtils.isNotBlank(image)) {
								images.add(getRealImage(image));
							}
						}
					}
				}
				map.put("introduction", introduction);
				map.put("images", images);
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 首页信息
	 * @param req
	 * @return
	 */
	@PostMapping("/indexInfo")
	@ResponseBody
	public ResJson indexInfo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		//定义显示
		res.put("taobao","0.3");
		res.put("jd","0.35");
		res.put("taobao","0.35");
		res.put("whp","0.35");
		try {
			// 新消息
			String isMsg = "0";
			if (StringUtils.isNotBlank(req.getUid())) {
				Member member = memberService.get(req.getUid());
				if (member != null) {
					res.put("isBindTb", "0");
					if(StringUtils.isNotBlank(member.getRelationId())){
						res.put("isBindTb", "1");
						res.put("relationId", member.getRelationId());
					}
				}
				// 获取未读消息
				isMsg = msgService.executeGetSql("SELECT COUNT(*) FROM t_msg WHERE uid = '"+req.getUid()+"' AND state = '0'").toString();
			}
			res.put("isMsg", isMsg);
			//判断来源
			if(!req.containsKey("type")||req.getString("type").equals("")){
				req.put("type","app");
			}
			// 轮播图列表
			List<Map<String, String>> bannerList = Lists.newArrayList();
			Banner banner = new Banner();
			banner.setType("0");
			List<Banner> list = bannerService.findList(banner);
			for (Banner b : list) {
				Map<String, String> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getImage()));
				map.put("category", b.getCategory());
				map.put("url", b.getUrl());
				map.put("productId", b.getProduct() != null ? b.getProduct().getId() : "");
				map.put("storeId", b.getStore() != null ? b.getStore().getId() : "");
				map.put("thirdLink", StringUtils.isNotBlank(b.getThirdLink()) ? b.getThirdLink() : "");
				map.put("productCategoryId", b.getProductCategory() != null ? b.getProductCategory().getId() : "");
				map.put("productCategoryName", b.getProductCategory() != null ? b.getProductCategory().getName() : "");
				bannerList.add(map);
			}
			res.put("bannerList", bannerList);

			// 活动列表
			List<Map<String, String>> activityList = Lists.newArrayList();
			Activity activity = new Activity();
			activity.setState("0");
			List<Activity> listact = activityService.findList(activity);
			for (Activity b : listact) {
				Map<String, String> map = Maps.newHashMap();
				map.put("image", getRealImage(b.getIcon()));
				map.put("title", b.getTitle());
				map.put("type", b.getType());
				map.put("link", StringUtils.isNotBlank(b.getLink()) ? b.getLink() : "");
				map.put("actid", b.getActid() != null ? b.getActid() : "");
				activityList.add(map);
			}
			res.put("activityList", activityList);

			// 类别列表
			List<Map<String, String>> categorywxappList = Lists.newArrayList();
			List<Map<String, String>> categoryappList = Lists.newArrayList();

			List<Button> buttonList = apiService.findButtonList();
			//List<Button> buttonList = buttonService.findList(new Button());
			for (Button button : buttonList) {
				Map<String, String> map = Maps.newHashMap();
				map.put("type", button.getType());
				map.put("icon", getRealImage(button.getIcon()));
				map.put("name", button.getTitle());
				if(button.getWxappshow().toString().equals("1")){
					categorywxappList.add(map);
				}
				if(button.getAppshow().toString().equals("1")){
					categoryappList.add(map);
				}
			}
			if(req.getString("type").equals("wxapp")){
				res.put("categoryList", categorywxappList);
			}else{
				res.put("categoryList", categoryappList);
			}
			// 公告列表
			List<Map<String, String>> announcementList = Lists.newArrayList();
			Notice notice = new Notice();
			notice.setType("1");
			List<Notice> noticeList = noticeService.findList(notice);
			for (Notice n : noticeList) {
				Map<String, String> map = Maps.newHashMap();
				map.put("title", n.getTitle());
				map.put("contentUrl", n.getUrl());
				announcementList.add(map);
			}
			res.put("announcementList", announcementList);

			// 推荐商品列表
			JSONArray recommendList = apiService.findIndexRecommendList();
			/*Map<String, String> params = Maps.newHashMap();
			params.put("material_id", "13366");// 综合
			params.put("page_no", req.getPageNo() + "");// 第几页，默认：１
			params.put("page_size", req.getPageSize() + "");// 页大小，默认20，1~100
			JSONObject result = DingdanxiaUtils.dingdanxiaAPI(DingdanxiaUtils.optimus, params);
			System.out.println("result:" + result.toString());
			if (!"200".equals(result.getString("code"))) {
				res.setResultNote(result.getString("msg"));
				return res;
			}
			JSONArray recommendList = result.getJSONArray("data");*/
			res.put("recommendList", recommendList);

			// 功能入口图片
			String msIcon = "";
			String byIcon = "";
			String sgIcon = "";
			String dqIcon = "";
			String yxIcon = "";
			String fpIcon = "";
			List<Access> accessList = apiService.findAccessList();
			//List<Access> accessList = accessService.findList(new Access());
			for (Access access : accessList) {
				if (StringUtils.isNotBlank(access.getImage())) {
					// 类型 1限时秒杀 2-9.9包邮 3品牌闪购 4抖券 5跨境优选 8.扶贫
					if ("1".equals(access.getType())) {
						msIcon = getRealImage(access.getImage());
					} else if ("2".equals(access.getType())) {
						byIcon = getRealImage(access.getImage());
					} else if ("3".equals(access.getType())) {
						sgIcon = getRealImage(access.getImage());
					} else if ("4".equals(access.getType())) {
						dqIcon = getRealImage(access.getImage());
					} else if ("5".equals(access.getType())) {
						yxIcon = getRealImage(access.getImage());
					}else if ("8".equals(access.getType())) {
						fpIcon = getRealImage(access.getImage());
					}
				}
			}
			res.put("msIcon", msIcon);
			res.put("byIcon", byIcon);
			res.put("sgIcon", sgIcon);
			res.put("dqIcon", dqIcon);
			res.put("yxIcon", yxIcon);
			res.put("fpIcon", fpIcon);

			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 我惠学院列表
	 * @param req
	 * @return
	 */
	@PostMapping("/collegeList")
	@ResponseBody
	public ResJson collegeList(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("获取失败");
		List<Map<String, String>> dataList = Lists.newArrayList();
		try {
			Page<College> page = collegeService.findPage(new Page<>(req.getPageNo(), req.getPageSize()), new College());
			res.setTotalPage(page.getTotalPage());
			for (College college : page.getList()) {
				Map<String, String> map = Maps.newHashMap();
				map.put("title", college.getTitle());
				map.put("image", getRealImage(college.getImage()));
				map.put("contentUrl", college.getUrl());
				map.put("adtime", DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(college.getUpdateDate()));
				dataList.add(map);
			}
			res.setDataList(dataList);
			res.setResult("0");
			res.setResultNote("获取成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 根据手机号获取guid
	 * @param req
	 * @return
	 */
	@PostMapping("/GetUInfoByPhone")
	@ResponseBody
	public ResJson GetUInfoByPhone(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败");
		try {
			if (isBlank(req.getString("phone"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("Phone", req.getString("phone")));
			JSONObject object = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResult("1");
				res.setResultNote(object.getString("respMsg"));
				return res;
			}
			JSONArray array = object.getJSONArray("data");
			JSONObject data = array.getJSONObject(0);
			String wohuiGuid = data.getString("C_GUID");
			res.put("wohuiGuid",wohuiGuid);
			res.setResult("0");
			res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 忘记密码
	 * @param req
	 * @return
	 */
	@PostMapping("/findUserPassword")
	@ResponseBody
	public ResJson findUserPassword(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("操作失败");
		try {
			if (isBlank(req.getString("phoneNum"), req.getString("code"), req.getString("password"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			// 判断验证码
			String captcha = getCaptcha(req.getString("phoneNum"));
			if (!req.getString("code").equals(captcha)) {
				res.setResultNote("验证码错误或已过期");
				return res;
			}

			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("Phone", req.getString("phoneNum")));
			JSONObject object = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote(object.getString("respMsg"));
				return res;
			}
			JSONArray array = object.getJSONArray("data");
			JSONObject data = array.getJSONObject(0);

			list.clear();
			list.add(new WohuiEntity("CardGUID", data.getString("C_GUID")));
			list.add(new WohuiEntity("NewPwd", req.getString("password")));
			list.add(new WohuiEntity("Action", "LOGIN"));
			JSONObject result = WohuiUtils.send(WohuiUtils.FindPwd, list);
			if (!"0000".equals(result.getString("respCode"))) {
				res.setResultNote(result.getString("respMsg"));
				return res;
			} else {
				res.setResult("0");
				res.setResultNote("操作成功");
			}
			/*
			// 根据手机号获取用户
			Member member = memberService.getByPhone(req.getString("phoneNum"));
			if (member == null) {
				res.setResultNote("该手机号未注册");
				return res;
			}

			member.setPassword(req.getString("password"));
			memberService.save(member);*/

			// 清除验证码
			removeCaptcha(req.getString("phoneNum"));
			//res.setResult("0");
			//res.setResultNote("操作成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 绑定手机号
	 * @param req
	 * @return
	 */
	@PostMapping("/addUserInfo")
	@ResponseBody
	public synchronized ResJson addUserInfo(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("绑定失败");
		try {
			if (isBlank(req.getString("thirdUid"), req.getString("type"), req.getString("phoneNum"), req.getString("code"), req.getString("province"), req.getString("city"), req.getString("area"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			// 判断验证码
			String captcha = getCaptcha(req.getString("phoneNum"));
			if (!req.getString("code").equals(captcha)) {
				res.setResultNote("验证码错误或已过期");
				return res;
			}

			Member member = null;
			if ("1".equals(req.getString("type"))) {// 微信
				member = memberService.findUniqueByProperty("wxid", req.getString("thirdUid"));
			} else if ("2".equals(req.getString("type"))) {// QQ
				member = memberService.findUniqueByProperty("qqid", req.getString("thirdUid"));
			} else if ("3".equals(req.getString("type"))) {// 支付宝
				member = memberService.findUniqueByProperty("aliid", req.getString("thirdUid"));
			}
			if (member != null && StringUtils.isNotBlank(member.getId())) {
				res.setResultNote("该三方ID已存在");
				return res;
			}

			// 根据手机号查询用户
			member = memberService.getByPhone(req.getString("phoneNum"));
			if (member != null) {// 更新
				if ("1".equals(req.getString("type"))) {// 微信
					if (StringUtils.isNotBlank(member.getWxid())) {
						res.setResultNote("该手机号已绑定微信");
						return res;
					}
					member.setWxid(req.getString("thirdUid"));
				} else if ("2".equals(req.getString("type"))) {// QQ
					if (StringUtils.isNotBlank(member.getQqid())) {
						res.setResultNote("该手机号已绑定QQ");
						return res;
					}
					member.setQqid(req.getString("thirdUid"));
				} else if ("3".equals(req.getString("type"))) {// 支付宝
					if (StringUtils.isNotBlank(member.getAliid())) {
						res.setResultNote("该手机号已绑定支付宝");
						return res;
					}
					member.setAliid(req.getString("thirdUid"));
				}
				if (StringUtils.isBlank(member.getIcon())) {
					member.setIcon(req.getString("userIcon"));
				}
			} else {// 插入
				// 会员系统注册
				List<WohuiEntity> list = Lists.newArrayList();
				list.add(new WohuiEntity("Phone", req.getString("phoneNum")));
				list.add(new WohuiEntity("Code", req.getString("code")));
				list.add(new WohuiEntity("SenderGUID", wohuiId));
				list.add(new WohuiEntity("Province", req.getString("province")));
				list.add(new WohuiEntity("City", req.getString("city")));
				list.add(new WohuiEntity("District", req.getString("area"), false));
				JSONObject object = WohuiUtils.send(WohuiUtils.PhoneReg, list);
				/*if (!"0000".equals(object.getString("respCode"))) {
					res.setResultNote(object.getString("respMsg"));
					return res;
				}*/
				JSONArray data = object.getJSONArray("data");
				JSONObject obj = data.getJSONObject(0);
				member = new Member();
				member.setIsNewRecord(true);
				member.setId(obj.getString("C_GUID"));
				member.setNumber(obj.getString("C_Number"));
				member.setRoles(obj.getString("C_Roles"));
				member.setPhone(req.getString("phoneNum"));
				member.setNickname("用户" + StringUtils.right(req.getString("phoneNum"), 4));
				member.setPassword(obj.getString("C_LoginPwd"));
				//member.setProvince(req.getString("province"));
				//member.setCity(req.getString("city"));
				//member.setArea(req.getString("area"));
				member.setState("0");
				member.setPoint("0");
				//member.setToken(req.getString("token"));
				member.setInvite(new Member(wohuiId));

				if ("1".equals(req.getString("type"))) {// 微信
					member.setWxid(req.getString("thirdUid"));
				} else if ("2".equals(req.getString("type"))) {// QQ
					member.setQqid(req.getString("thirdUid"));
				} else if ("3".equals(req.getString("type"))) {// 支付宝
					member.setAliid(req.getString("thirdUid"));
				}
				member.setIcon(req.getString("userIcon"));
			}
			member.setProvince(req.getString("province"));
			member.setCity(req.getString("city"));
			member.setArea(req.getString("area"));
			member.setToken(req.getString("token"));
			memberService.save(member);

			// 去token
			if (!isBlank(req.getString("token"))) {
				memberService.executeUpdateSql("UPDATE t_member SET token = NULL WHERE token = '"+req.getString("token")+"' AND id != '"+member.getId()+"'");
			}

			// 清除验证码
			removeCaptcha(member.getPhone());

			res.put("uid", member.getId());
			res.setResult("0");
			res.setResultNote("绑定成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 第三方登录（微信，QQ，支付宝）
	 * @param req
	 * @return
	 */
	@PostMapping("/thirdLogin")
	@ResponseBody
	public ResJson thirdLogin(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("登录失败");
		try {
			if (isBlank(req.getString("thirdUid"), req.getString("type"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			Member member = null;
			if ("1".equals(req.getString("type"))) {// 微信
				member = memberService.findUniqueByProperty("wxid", req.getString("thirdUid"));
			} else if ("2".equals(req.getString("type"))) {// QQ
				member = memberService.findUniqueByProperty("qqid", req.getString("thirdUid"));
			} else if ("3".equals(req.getString("type"))) {// 支付宝
				member = memberService.findUniqueByProperty("aliid", req.getString("thirdUid"));
			}

			if (member == null || StringUtils.isBlank(member.getId())) {
				res.put("isBind", "0");
			} else {
				res.put("isBind", "1");
				if(StringUtils.isNotBlank(member.getRelationId())){
					res.put("isBindTb", "1");
					res.put("relationId", member.getRelationId());
				}else{
					res.put("isBindTb", "0");
				}
				res.put("uid", member.getId());
				res.put("pddId", member.getPddId());

				// 去token
				if (!isBlank(req.getString("token"))) {
					member.setToken(req.getString("token"));
					memberService.save(member);
					memberService.executeUpdateSql("UPDATE t_member SET token = NULL WHERE token = '"+req.getString("token")+"' AND id != '"+member.getId()+"'");
				}
			}
			res.setResult("0");
			res.setResultNote("登录成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 用户登录
	 * @param req
	 * @return
	 */
	@PostMapping("/userLogin")
	@ResponseBody
	public ResJson userLogin(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("登录失败");
		try {
			if (isBlank(req.getString("phoneNum"), req.getString("password"))) {
				res.setResultNote("参数不完整");
				return res;
			}

			// 根据手机号查询用户信息
			/*Member member = memberService.getByPhone(req.getString("phoneNum"));
			if (member == null || !req.getString("password").equals(member.getPassword())) {
				res.setResultNote("账号或密码错误");
				return res;
			}*/
			String  IP="";
			String  OSInfo="";
			if(req.getString("ip") !=null && StringUtils.isNotBlank(req.getString("ip"))){
				IP=req.getString("ip");
			}
			if(req.getString("osinfo") !=null && StringUtils.isNotBlank(req.getString("osinfo"))){
				OSInfo=req.getString("osinfo");
			}

			// 调用三方
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("Name", req.getString("phoneNum")));
			list.add(new WohuiEntity("Pwd", req.getString("password")));
			list.add(new WohuiEntity("IP",IP ));
			list.add(new WohuiEntity("OSInfo", OSInfo));
			JSONObject object = WohuiUtils.send(WohuiUtils.ULogin, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote(object.getString("respMsg"));
				return res;
			}
			JSONArray data = object.getJSONArray("data");
			JSONObject obj = data.getJSONObject(0);
			String msg = obj.getString("UMsg");
			if ("no_Name".equalsIgnoreCase(msg)) {
				res.setResultNote("账号不存在");
				return res;
			}
			if ("fail_pwd".equalsIgnoreCase(msg)) {
				res.setResultNote("账号或密码错误");
				return res;
			}
			if ("fail_State".equalsIgnoreCase(msg)) {
				res.setResultNote("账户被锁定");
				return res;
			}

			if ("success".equalsIgnoreCase(msg) || "no_WS".equalsIgnoreCase(msg)) {
				Member member = memberService.get(obj.getString("UGUID"));
				//清除绑定的openid
				//ene
				if (member != null) {
					member.setNumber(obj.getString("Unumber"));
					member.setPhone(obj.getString("UPhone"));
					member.setRoles(obj.getString("URoles"));
					member.setToken(req.getString("token"));
				} else {
					// 查询会员信息
					List<WohuiEntity> temp = Lists.newArrayList();
					temp.add(new WohuiEntity("UGUID", obj.getString("UGUID")));
					JSONObject jsonObject = WohuiUtils.send(WohuiUtils.GetUInfoByGUID, temp);
					if (!"0000".equals(jsonObject.getString("respCode"))) {
						res.setResultNote(jsonObject.getString("respMsg"));
						return res;
					}
					JSONArray jsonArray = jsonObject.getJSONArray("data");
					JSONObject o = jsonArray.getJSONObject(0);

					member = new Member();
					member.setIsNewRecord(true);
					member.setId(o.getString("C_GUID"));
					member.setNumber(o.getString("C_Number"));
					member.setRoles(o.getString("C_Roles"));
					member.setPhone(o.getString("C_Phone"));
					member.setNickname(StringUtils.isNotBlank(o.getString("C_RealName")) ? o.getString("C_RealName") : "用户" + StringUtils.right(o.getString("C_Phone"), 4));
					member.setPassword(o.getString("C_LoginPwd"));
					member.setProvince(o.getString("C_Province"));
					member.setCity(o.getString("C_City"));
					member.setArea(o.getString("C_District"));
					member.setState("0");
					member.setPoint("0");
					member.setToken(req.getString("token"));
					member.setInvite(new Member(o.getString("C_Sender")));
				}
				memberService.save(member);

				// 去token
				if (!isBlank(req.getString("token"))) {
					memberService.executeUpdateSql("UPDATE t_member SET token = NULL WHERE token = '"+req.getString("token")+"' AND id != '"+member.getId()+"'");
				}
				if(StringUtils.isNotBlank(member.getRelationId())){
					res.put("isBindTb", "1");
					res.put("relationId", member.getRelationId());
				}else{
					res.put("isBindTb", "0");
				}
				res.put("uid", member.getId());
				res.put("pddId", member.getPddId());
				res.setResult("0");
				res.setResultNote("登录成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 发送验证码
	 * @param req
	 * @return
	 */
	@PostMapping("/sendSms")
	@ResponseBody
	public ResJson sendSms(@RequestBody ReqJson req, HttpServletRequest request) {
		ResJson res = new ResJson();
		res.setResultNote("发送失败");
		try {
//			String Sign=req.getString("Sign");//签名
			String phone = req.getString("phoneNum");//手机号
			String type = req.getString("type");//类型
			//验证签名
//			if(!ToolsUtil.VerfySign(phone+type,Sign)){
//				res.setResultNote("签名错误！");
//				return res;
//			}
			//手机号
			if (StringUtils.isBlank(phone)) {
				res.setResultNote("请输入手机号");
				return res;
			}
			// 判断手机号是否频繁请求（同一手机号一分钟内请求一次）
			String phoneCache = (String) CacheProviderHolder.getLevel2Cache("phoneCache").get(phone);
			if (StringUtils.isNotBlank(phoneCache)) {
				res.setResultNote("您请求过于频繁，请稍候再试！");
				return res;
			}
			// 判断IP（同一个ip如果一天发送超过20次就拉黑）
			String ip = IPUtil.getRemoteAddress(request);
			JSONObject json = (JSONObject)CacheProviderHolder.getLevel2Cache("ipCache").get(ip);
			if (json == null) {
				json = new JSONObject();
				json.put("time", System.currentTimeMillis());
				json.put("count", 1);
			} else {
				// 判断次数
				int count = json.getIntValue("count");
				if (count > 20) {
					CacheProviderHolder.getLevel2Cache("ipCache").put(ip, json);
					System.out.println("-------------------------------------------------------");
					System.out.println("疑似攻击客户端ip"+ip+"--手机号"+phone);
					System.out.println("-------------------------------------------------------");
					return res;
				}
				// 判断时间
				long time = json.getLongValue("time");
				if (System.currentTimeMillis() - time > 86400000) {
					json.put("time", System.currentTimeMillis());
					json.put("count", 1);
				} else {
					json.put("count", count+1);
				}
			}
			CacheProviderHolder.getLevel2Cache("ipCache").put(ip, json, 86400);

			if (!PhoneUtils.isMobile(phone)) {
				res.setResultNote("手机号格式错误");
				return res;
			}
			removeCaptcha(phone);

			String code1 = RandomUtil.randomNumberFixLength(1);
			String code2 = RandomUtil.randomNumberFixLength(1);
			while (code2.equals(code1)) {
				code2 = RandomUtil.randomNumberFixLength(1);
			}
			String code = code1 + code1 + code1 + code2 + code2 + code2;
			setCaptcha(phone, code, 900);

			// 对接三方接口
			// 类型 0普通验证码(默认0) 1注册验证码 2绑定手机号 3申请信用卡 4更换手机号 5找回密码
			String content = "您的验证码是" + code + "，有效期15分钟。";// 短信内容
			if ("1".equals(req.getString("type"))) {
				content = "您的验证码为：" + code + "，验证码即为您的初始密码。我惠云店：除了省钱！啥都不会，除了好货，啥都没有！";
			} else if ("2".equals(req.getString("type"))) {
				content = "您的验证码为：" + code + "。我惠云店：除了省钱！啥都不会，除了好货，啥都没有！";
			} else if ("3".equals(req.getString("type"))) {
				content = "您正在通过我惠省钱APP申请银行信用卡，验证码为"+code+"，有效期15分钟，请勿向任何人提供您收到的验证码。";
			} else if ("4".equals(req.getString("type"))) {
				content = "您正在绑定我惠账号，验证码为"+code+"，有效期15分钟，请勿向任何人提供您收到的验证码。";
			} else if ("5".equals(req.getString("type"))) {
				content = "您正在重置登录密码，验证码"+code+"，有效期为15分钟，请勿向任何人提供您收到的验证码。";
			}

			JSONObject object = FeigeSMSUtil.sendSms(phone, content);
			logger.info(object.toString());
			if ("0".equals(object.getString("Code"))) {
				res.setResult("0");
				res.setResultNote("发送成功");
			} else {
				res.put("resultNote", object.getString("Message"));
			}
			CacheProviderHolder.getLevel2Cache("phoneCache").put(phone, phone, 60);// 记录请求时间
			// res.put("code", code);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 用户注册
	 * @param req
	 * @return
	 */
	@PostMapping("/userRegister")
	@ResponseBody
	public synchronized ResJson userRegister(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("注册失败");
		try {
			if (isBlank(req.getString("phoneNum"), req.getString("code"), req.getString("province"), req.getString("city"), req.getString("area"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			// 判断验证码
			String captcha = getCaptcha(req.getString("phoneNum"));
			if (!req.getString("code").equals(captcha)) {
				res.setResultNote("验证码错误或已过期");
				return res;
			}

			// 判断手机号是否可用
			if (!apiService.checkPhone(req.getString("phoneNum"))) {
				res.setResultNote("该手机号已存在");
				return res;
			}
			String invite = "35278AE6B4E14F1F9582937C5C836453";
			Member invitemember =null;
			if (StringUtils.isNotBlank(req.getString("inviteId"))) {
				invitemember = memberService.get(req.getString("inviteId"));
				invite = req.getString("inviteId");
			}
			if (invitemember == null) {
				invitemember = new Member(wohuiId);
			}
			// 调用三方
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("Phone", req.getString("phoneNum")));
			list.add(new WohuiEntity("Code", req.getString("code")));
			list.add(new WohuiEntity("SenderGUID", invite));
			list.add(new WohuiEntity("Province", req.getString("province")));
			list.add(new WohuiEntity("City", req.getString("city")));
			list.add(new WohuiEntity("District", req.getString("area"), false));
			JSONObject object = WohuiUtils.send(WohuiUtils.PhoneReg, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote(object.getString("respMsg"));
				return res;
			}
			JSONArray data = object.getJSONArray("data");
			JSONObject obj = data.getJSONObject(0);
			Member member = new Member();
			member.setIsNewRecord(true);
			member.setId(obj.getString("C_GUID"));
			member.setNumber(obj.getString("C_Number"));
			member.setRoles(obj.getString("C_Roles"));
			member.setPhone(req.getString("phoneNum"));
			member.setNickname("用户" + StringUtils.right(req.getString("phoneNum"), 4));
			member.setPassword(obj.getString("C_LoginPwd"));
			member.setProvince(req.getString("province"));
			member.setCity(req.getString("city"));
			member.setArea(req.getString("area"));
			member.setState("0");
			member.setPoint("0");
			member.setToken(req.getString("token"));
			member.setInvite(invitemember);
			//调用喵有券创建推广位接口
			String pid="";
			Map<String, String> params = Maps.newHashMap();
			params.put("pdname", MiaoyouquanUtils.pdname);
			params.put("number", "1");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if ("200".equals(jsonObject.getString("code"))) {
				JSONObject dataObject=jsonObject.getJSONObject("data");
				if(dataObject!=null){
					JSONArray pidList=dataObject.getJSONArray("p_id_list");
					if(pidList!=null && pidList.size()>0){
						pid=pidList.getJSONObject(0).getString("p_id");
						member.setPddId(pid);
					}
				}
			}
			memberService.save(member);

			// 去token
			if (!isBlank(req.getString("token"))) {
				memberService.executeUpdateSql("UPDATE t_member SET token = NULL WHERE token = '"+req.getString("token")+"' AND id != '"+member.getId()+"'");
			}

			// 清除验证码
			removeCaptcha(member.getPhone());

			// 发送消息
			// 获取消息文案
			MsgExample msgExample = msgExampleService.getByType("1");
			if (msgExample != null) {
				msgService.insert(member, "系统消息", msgExample.getContent());
			}
			// 给邀请人发消息
			MsgExample example = msgExampleService.getByType("2");
			if (example != null) {
				msgService.insert(member.getInvite(), "系统消息", example.getContent());
			}

			res.put("pddId", pid);
			res.put("uid", member.getId());
			res.setResult("0");
			res.setResultNote("注册成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}

	/**
	 * 检测是否为空
	 * @param values
	 * @return
	 */
	private boolean isBlank(String...values) {
		for (String value : values) {
			if (StringUtils.isBlank(value)) {
				return true;
			}
		}
		return false;
	}
	/**
	 * 是否微信浏览器
	 * @Title: isWechat
	 * @author: pk
	 * @Description: TODO
	 * @param request
	 * @return
	 * @return: boolean
	 */
	public static boolean isWechat(HttpServletRequest request) {
		String ua = request.getHeader("User-Agent").toLowerCase();
		if (ua.indexOf("micromessenger") > -1) {
			return true;//微信
		}
		return false;//非微信手机浏览器

	}

	/**
	 * 判断 移动端/PC端
	 * @Title: isMobile
	 * @author: pk
	 * @Description: TODO
	 * @param request
	 * @return
	 * @return: boolean
	 */
	public static boolean isMobile(HttpServletRequest request) {
		List<String> mobileAgents = Arrays.asList("ipad", "iphone os", "rv:1.2.3.4", "ucweb", "android", "windows ce", "windows mobile");
		String ua = request.getHeader("User-Agent").toLowerCase();
		for (String sua : mobileAgents) {
			if (ua.indexOf(sua) > -1) {
				return true;//手机端
			}
		}
		return false;//PC端
	}
	/**
	 * 获取图片真实路径
	 * @param image
	 * @return
	 */
	private String getRealImage(String image) {
		if (StringUtils.isNotBlank(image)) {
			if (image.startsWith("http")) {
				return image;
			}
			return filePath + image;
		}
		return "";
	}

	/**
	 * 向二级缓存中保存手机号验证码
	 * @param phone 手机号
	 * @param code 验证码
	 * @param i 有效时长(秒)
	 */
	private void setCaptcha(String phone, String code, int i) {
		CacheProviderHolder.getLevel2Cache(UserUtils.CAPTCHA_CACHE).put(phone, code, i);
	}

	/**
	 * 根据手机号获取缓存中的验证码
	 * @param phone
	 * @return
	 */
	private String getCaptcha(String phone) {
		return (String) CacheProviderHolder.getLevel2Cache(UserUtils.CAPTCHA_CACHE).get(phone);
	}

	/**
	 * 清除缓存中指定手机号的验证码
	 * @param phone
	 */
	private void removeCaptcha(String phone) {
		CacheProviderHolder.getLevel2Cache(UserUtils.CAPTCHA_CACHE).evict(phone);
	}

	/**
	 * 手机号验证
	 *
	 * @param  mobile 手机号
	 * @return 验证通过返回true
	 *//*
    public static boolean isMobile(String mobile) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$"); // 验证手机号
        m = p.matcher(mobile);
        b = m.matches();
        return b;
    }  */
}
